Class Array

Additional static members for the native Array class.

Does not extend the native Array class.

Constructors

Methods

  • WARNING:EXPERIMENTAL Deep clone an array, and return the result.

    Shortcut of xjs_Object.cloneDeep, but for arrays. Warning: passing in a sparse array can yield unexpected results.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      the array to clone

    Returns T[]

    an exact copy of the given array

    Typeparam

    T - the type of elements in arr

  • Test whether an array is a subarray of another array.

    This method acts like String#includes, testing whether the elements in the smaller array appear consecutively and in the same order as in the larger array. In other words, if {@link xjs_Array.is}(larger.slice(a,b), smaller) (for some integers a and b), then this method returns true. Warning: passing in sparse arrays can yield unexpected results.

    Elements are compared via the provided predicate. If no predicate is provided, this method uses the default predicate xjs_Object.sameValueZero.

    'twofoursix'.includes('wofo')===true
    xjs.Array.contains([2,'w','o',4,'o','u','r',6,'i','x'], ['w','o',4,'o'])===true
    xjs.Array.contains([2,'w','o',4,'o','u','r',6,'i','x'], ['o','u'])===true
    xjs.Array.contains([2,'w','o',4,'o','u','r',6,'i','x'], [6,'o','u','r'])===false // not in the same order
    xjs.Array.contains([2,'w','o',4,'o','u','r',6,'i','x'], [2,4,6])===false // not consecutive
    xjs.Array.contains([2,4,6], [2,4,6,8]) // throws a RangeError: first array is smaller than second

    Type Parameters

    • T

    Parameters

    • larger: readonly T[]

      the larger array, to test against

    • smaller: readonly T[]

      the smaller array, to test

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of larger and smaller

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    is smaller a subarray of larger?

    Typeparam

    T - the type of elements in larger and smaller

    Throws

    if the second array is larger than the first

    Deprecated

    use xjs_Array.isConsecutiveSuperarrayOf instead.

  • Remove the ‘holes’ in an array.

    (Make a sparse array dense, or keep a dense array dense). This method is Pure — it does not modify the given argument.

    A sparse array is an array whose length is greater than the number of elements its contains. For example, new Array(4) is a sparse array: it has a length of 4 but no elements. Sparse arrays are said to have a ‘hole’ where there is an index but no element. A dense array is an array whose length is equal to its number of elements.

    Note that accessor notation is not sufficient to detect sparseness: calling new Array(4)[0] will return undefined, even though undefined is not an element in the array.

    For example, const arr = ['a', 'b', , 'd'] is a sparse array because arr[2] has not been defined. Evaluating arr[2] will yield undefined, even though it has not been explicitly declared so.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      an array to make dense

    Returns T[]

    a copy of the given array, but with no ‘holes’; the returned array might have a smaller length than the argument

    Typeparam

    T - the type of elements in arr

  • Fill the ‘holes’ in an array with a given value.

    This method is Pure — it does not modify the given argument.

    Similar to xjs_Array.densify, but instead of removing the holes of a sparse array (thus decreasing the length), this method fills the holes with a given value, thus maintaining the original array’s length.

    Warning: This method has an important side-effect: It treats entries of undefined as ‘holes’, even if they were intentionally declared. Therefore this method is not well-suited for arrays with intentional entries of undefined. Suggestion: replace all intentional entries of undefined with null.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      an array whose ‘holes’ and undefineds to fill, if it has any

    • value: T

      the value to fill in the holes

    Returns T[]

    a copy of the given array, but with all holes and undefineds filled; the returned array will have the same length as the argument

    Typeparam

    T - the type of elements in arr

  • Asynchronous Array#filter.

    Type Parameters

    • T

    Parameters

    • arr: T[]

      the array to filter

    • predicate: ((ele, idx, ary) => boolean | Promise<boolean>)

      function to test each element of the array

        • (ele, idx, ary): boolean | Promise<boolean>
        • Parameters

          • ele: T
          • idx: number
          • ary: T[]

          Returns boolean | Promise<boolean>

    • this_arg: unknown = null

      object to use as this when executing predicate

    Returns Promise<T[]>

    a new array with the elements that pass the test; if no elements pass, an empty array is returned

    Typeparam

    T - the type of elements in the array

  • Asynchronous Array#find.

    Type Parameters

    • T

    Parameters

    • arr: T[]

      the array to search

    • predicate: ((ele, idx, ary) => boolean | Promise<boolean>)

      function to test each element of the array

        • (ele, idx, ary): boolean | Promise<boolean>
        • Parameters

          • ele: T
          • idx: number
          • ary: T[]

          Returns boolean | Promise<boolean>

    • this_arg: unknown = null

      object to use as this when executing predicate

    Returns Promise<null | T>

    the item found, or null if none is found

    Typeparam

    T - the type of elements in the array

  • Perform a callback function on an array, aggregating any errors caught.

    Instead of throwing on the first error and stopping iteration, as Array#forEach would do, this method continues performing the callback on the rest of the array until all items are done. If only one error was caught, then that error is simply rethrown. However, if more errors were caught, they are collected into a single AggregateError, which is then thrown. If no errors are caught, this method returns void.

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      the array of items

    • callback: ((item, i, src) => void)

      the function to call on each item

        • (item, i, src): void
        • Parameters

          • item: T
          • i: number
          • src: readonly T[]

          Returns void

    Returns void

    Example

    xjs.Array.forEachAggregated<number>([1, 2, 3, 4], (n) => {
    if (n % 2 === 0) {
    throw new Error(`${ n } is even.`);
    };
    });
    // Expected thrown error:
    AggregateError {
    errors: [
    Error { message: "2 is even." },
    Error { message: "4 is even." },
    ]
    }

    Typeparam

    T the type of items in the array

    Throws

    if two or more iterations throws an error

    Throws

    if one iteration throws an error

  • Executes a callback on each item of an array until that callback returns.

    If any iteration throws, the error is stored, and execution proceeds to the next iteration. If any iteration returns, this method returns void and the errors are discarded. If all iterations throw, the stored errors are collected into a single AggregateError, which is then thrown. (If there is only one error stored then it is simply rethrown.)

    The “dual” of Array#forEach — this method returns as soon as a callback call is successful; otherwise throws.

    Similar to Promise.any, but synchronous.

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      the array of items

    • callback: ((item, i, src) => void)

      the function to call on each item

        • (item, i, src): void
        • Parameters

          • item: T
          • i: number
          • src: readonly T[]

          Returns void

    Returns void

    Example

    let update = 0;
    xjs.Array.forEither<number>([1, 2, 3, 4], (n) => {
    update = n;
    if (n % 2 === 0) {
    throw new Error(`${ n } is even.`);
    }
    });
    // Expected result:
    assert.strictEqual(update, 1);

    Typeparam

    T the type of items in the array

    Throws

    if two or more iterations throws an error

    Throws

    if one iteration throws an error

  • Deep freeze an array, and return the result.

    Shortcut of xjs_Object.freezeDeep, but for arrays. Warning: passing in a sparse array can yield unexpected results. Note: This function is impure, modifying the given argument.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      the array to freeze

    Returns readonly T[]

    the given array, with everything frozen

    Deprecated

    use interface readonly T[] instead

  • Get a value of an array, given an index.

    Same as arr[index], but more robust.

    Type Parameters

    • T

    Parameters

    • arr: T[]

      the array to search

    • index: number

      the index of the returned value

    Returns T

    the value in arr found at index

    Throws

    if the given index is NaN

    Throws

    if the index is out of bounds (or if the returned value is undefined)

  • Test whether two arrays have “the same” elements.

    Note: Use this method only if providing a predicate. If testing for “same-value-zero” equality (the default predicate), use Node.js’s built-in assert.deepStrictEqual() instead.

    Shortcut of xjs_Object.is, but for arrays. Warning: passing in sparse arrays can yield unexpected results.

    Type Parameters

    • T

    Parameters

    • a: readonly T[]

      the first array

    • b: readonly T[]

      the second array

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of a and b

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    Are corresponding elements the same, i.e. replaceable?

    Typeparam

    T - the type of elements in a and b

  • xjs_Array.isSubarrayOf, but the elements of a must appear consecutively in b.

    Type Parameters

    • U
    • T

    Parameters

    • a: readonly T[]

      the smaller array

    • b: readonly U[]

      the larger array

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of a and b

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    Is a a consecutive subarray of b?

    Typeparam

    T - the type of elements in a

    Typeparam

    U - the type of elements in b

  • xjs_Array.isConsecutiveSubarrayOf but with the parameters switched.

    Type Parameters

    • T
    • U

    Parameters

    • a: readonly T[]

      the larger array

    • b: readonly U[]

      the smaller array

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of a and b

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    exactly xjs_Array.isConsecutiveSubarrayOf(b, a, predicate)

    Typeparam

    T - the type of elements in a

    Typeparam

    U - the type of elements in b

  • Return whether a is a subarray of b.

    If and only if a is a subarray of b, all of the following must be true:

    • a cannot be larger than b
    • every element of a must appear somewhere in b, where comparison is determined by the predicate parameter
    • the elements of a that are in b must appear in the same order in which they appear in a

    Note that if a is an empty array [], or if a and b are “the same” (as determined by predicate), this method returns true.

    Type Parameters

    • U
    • T

    Parameters

    • a: readonly T[]

      the smaller array

    • b: readonly U[]

      the larger array

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of a and b

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    Is a a subarray of b?

    Typeparam

    T - the type of elements in a

    Typeparam

    U - the type of elements in b

  • xjs_Array.isSubarrayOf, but with the parameters switched.

    Type Parameters

    • T
    • U

    Parameters

    • a: readonly T[]

      the larger array

    • b: readonly U[]

      the smaller array

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of corresponding elements of a and b

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns boolean

    exactly xjs_Array.isSubarrayOf(b, a, predicate)

    Typeparam

    T - the type of elements in a

    Typeparam

    U - the type of elements in b

  • Map an array using a callback, aggregating any errors caught.

    Instead of throwing on the first error and stopping iteration, as Array#map would do, this method continues performing the callback on the rest of the array until all items are done. If only one error was caught, then that error is simply rethrown. However, if more errors were caught, they are collected into a single AggregateError, which is then thrown. If no errors are caught, this method returns the usual map.

    Type Parameters

    • T
    • U

    Parameters

    • array: readonly T[]

      the array of items

    • callback: ((item, i, src) => U)

      the function to call on each item

        • (item, i, src): U
        • Parameters

          • item: T
          • i: number
          • src: readonly T[]

          Returns U

    Returns U[]

    the array of mapped items

    Example

    xjs.Array.mapAggregated<number>([1, 2, 3, 4], (n) => {
    if (n % 2 === 1) {
    throw new Error(`${ n } is odd.`);
    } else {
    return n / 2;
    };
    });
    // Expected thrown error:
    AggregateError {
    errors: [
    Error { message: "1 is odd." },
    Error { message: "3 is odd." },
    ]
    }

    xjs.Array.mapAggregated<number>([2, 4, 6], (n) => {
    if (n % 2 === 1) {
    throw new Error(`${ n } is odd.`);
    } else {
    return n / 2;
    };
    });
    // Expected return value:
    [1, 2, 3]

    Typeparam

    T the type of items in the array

    Typeparam

    U the type of items returned by the mapping callback

    Throws

    if two or more iterations throws an error

    Throws

    if one iteration throws an error

  • Look at the top of a stack, without affecting the stack.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      the stack to peek

    Returns T

    the last entry of the array, if the array is nonempty

    Typeparam

    T - the type of elements in arr

    Throws

    if the array is empty

  • Make a copy of an array, and then remove duplicate entries.

    "Duplicate entries" are entries that considered "the same" by the provided predicate, or if none is given, xjs_Object.sameValueZero. Only duplicate entries are removed; the order of non-duplicates is preserved.

    Type Parameters

    • T

    Parameters

    • arr: readonly T[]

      an array to use

    • Optional predicate: ((x, y) => boolean)

      check the “sameness” of elements in the array

        • (x, y): boolean
        • Parameters

          Returns boolean

    Returns T[]

    a new array, with duplicates removed

    Typeparam

    T - the type of elements in arr

    Deprecated

    use [...new Set(arr)] instead