All files / src/utils arrays.ts

100% Statements 16/16
100% Branches 12/12
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                    1x 29x                             1x 796x 2x     794x 1x     793x 1172x 714x       79x                                 1x 123x 121x   2x      
/**
 * Flattens an array of arrays.
 *
 * @param T
 *   The type of the elements contained in the arrays.
 * @param {T[][]} elems
 *   An array of arrays.
 * @returns {T[]}
 *   A flattened array.
 */
export function flatten<T>(elems: T[][]): T[] {
  return [].concat.apply([], elems);
}
 
/**
 * Compare 2 arrays using `===`. No deep comparaison.
 *
 * @param T
 *   The type of the elements contained in the arrays.
 * @param {T[]} a
 *   First array.
 * @param {T[]} b
 *   Second array.
 * @return {boolean}
 *   True if `a` and `b` contains the same values in the same order.
 */
export function arrayEquals<T>(a: T[], b: T[]): boolean {
  if (!(Array.isArray(a) && Array.isArray(b))) {
    return false;
  }
 
  if (a.length !== b.length) {
    return false;
  }
 
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
 
  return true;
}
 
/**
 * Returns a new array with element at index `idx` replaced with `elem`.
 *
 * @param T
 *   The type of the elements contained in the array.
 * @param {T[]} elems
 *   The original array.
 * @param {number} idx
 *   The index at which to replace.
 * @param {T} elem
 *   The element to place at the specified index.
 * @return {T[]}
 *   A new array with the element replaced.
 */
export function replace<T>(elems: T[], idx: number, elem: T): T[] {
  if (idx >= 0 && idx < elems.length) {
    return [...elems.slice(0, idx), elem, ...elems.slice(idx + 1)];
  } else {
    return [...elems];
  }
}