import { assert } from "../../assert.js";

/**
 * Will invoke A.equals(B) on members if such exists
 * @template T,R
 * @param {T[]} first
 * @param {R[]} second
 * @return {boolean}
 */
export function isArrayEqual(first, second) {
    assert.defined(first, 'first');
    assert.isArray(first, 'first');

    assert.defined(second, 'second');
    assert.isArray(second, 'second');

    const element_count = first.length;

    if (element_count !== second.length) {
        // arrays are of different size
        return false;
    }

    let i = 0;

    for (; i < element_count; i++) {

        const a = first[i];
        const b = second[i];

        if (a === b) {
            continue;
        }

        if (
            a === undefined || a === null
            || b === undefined || b === null
        ) {
            // shortcut to avoid working with nulls and undefined values
            return false;
        }

        // try "equals" method
        if (typeof a === "object" && typeof a.equals === "function") {

            if (!a.equals(b)) {
                return false;
            }

        } else {
            return false;
        }

    }

    return true;

}
