All files reduce.ts

100% Statements 10/10
75% Branches 3/4
100% Functions 6/6
100% Lines 9/9

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 67 68 69 70 71 728x                                                                                 8x 2x     8x         4x   20x         8x                   8x 2x      
import { purry } from './purry';
 
/**
 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 * @param array the array to reduce
 * @param fn the callback function
 * @param initialValue the initial value to use as an accumulator value in the callback function
 * @signature
 *    P.reduce(items, fn, initialValue)
 *    P.reduce.indexed(items, fn, initialValue)
 * @example
 *    P.reduce([1, 2, 3, 4, 5], (acc, x) => acc + x, 100) // => 115
 *    P.reduce.indexed([1, 2, 3, 4, 5], (acc, x, i, array) => acc + x, 100) // => 115
 * @data_first
 * @indexed
 * @category Array
 */
export function reduce<T, K>(
  items: readonly T[],
  fn: (acc: K, item: T) => K,
  initialValue: K
): K;
 
/**
 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 * @param fn the callback function
 * @param initialValue the initial value to use as an accumulator value in the callback function
 * @signature
 *    P.reduce(fn, initialValue)(array)
 * @example
 *    P.pipe([1, 2, 3, 4, 5], P.reduce((acc, x) => acc + x, 100)) // => 115
 *    P.pipe([1, 2, 3, 4, 5], P.reduce.indexed((acc, x, i, array) => acc + x, 100)) // => 115
 * @data_last
 * @indexed
 * @category Array
 */
export function reduce<T, K>(
  fn: (acc: K, item: T) => K,
  initialValue: K
): (items: readonly T[]) => K;
 
export function reduce() {
  return purry(_reduce(false), arguments);
}
 
const _reduce = (indexed: boolean) => <T, K>(
  items: T[],
  fn: (acc: K, item: T, index?: number, items?: T[]) => K,
  initialValue: K
): K => {
  return items.reduce(
    (acc, item, index) =>
      indexed ? fn(acc, item, index, items) : fn(acc, item),
    initialValue
  );
};
 
export namespace reduce {
  export function indexed<T, K>(
    array: readonly T[],
    fn: (acc: K, item: T, index: number, items: T[]) => K,
    initialValue: K
  ): Record<string, T>;
  export function indexed<T, K>(
    fn: (acc: K, item: T, index: number, items: T[]) => K,
    initialValue: K
  ): (array: readonly T[]) => Record<string, T>;
  export function indexed() {
    return purry(_reduce(true), arguments);
  }
}