All files / src/core/utils arrays.ts

100% Statements 11/11
100% Branches 6/6
100% Functions 3/3
100% Lines 8/8

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                                                                699x 693x 2224x 321x     6x 13x   699x                 418x  
import { isArrayLike } from 'core/utils/types';
import { PlainObject } from 'core/typings';
 
/**
 * Iterates through a array or object
 * @param arrayLikeOrObject The array or object through which shall be iterated.
 * @param callback The function which is responsible for the iteration.
 * If the function returns true its treated like a "continue" statement.
 * If the function returns false its treated like a "break" statement.
 */
export function each<T>(
  array: Array<T> | ReadonlyArray<T>,
  callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | void,
): Array<T> | ReadonlyArray<T>;
export function each<T>(
  array: Array<T> | ReadonlyArray<T> | null,
  callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | void,
): Array<T> | ReadonlyArray<T> | null;
export function each<T>(
  arrayLikeObject: ArrayLike<T>,
  callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | void,
): ArrayLike<T>;
export function each<T>(
  arrayLikeObject: ArrayLike<T> | null,
  callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | void,
): ArrayLike<T> | null;
export function each(obj: PlainObject, callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | void): PlainObject;
export function each(obj: PlainObject | null, callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | void): PlainObject | null;
export function each<T>(
  source: ArrayLike<T> | PlainObject | null,
  callback: (value: T | any, indexOrKey: any, source: any) => boolean | void,
): Array<T> | ReadonlyArray<T> | ArrayLike<T> | PlainObject | null {
  if (isArrayLike(source)) {
    for (let i = 0; i < source.length; i++) {
      if (callback(source[i], i, source) === false) {
        break;
      }
    }
  } else if (source) {
    each(Object.keys(source), (key) => callback(source[key], key, source));
  }
  return source;
}
 
/**
 * Returns the index of the given inside the given array or -1 if the given item isn't part of the given array.
 * @param arr The array.
 * @param item The item.
 * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
 */
export const indexOf: <T = any>(arr: Array<T>, item: T, fromIndex?: number) => number = (arr, item, fromIndex) => arr.indexOf(item, fromIndex);