Programação Funcional com JavaScript

Reduce


export const reduce = defn(
  (fn, array, initial) => {
    if (array.length === 0)
      throw new Error(`Cannot reduce a empty array`);

    if (array.length === 1) return array[0];
    if (array.length === 2) return fn(array[0], array[1]);

    let result = initial === undefined ? array[0] : initial;
    const [head, ...tail] = array;

    for (const item of initial === undefined
      ? tail
      : [head, ...tail]) {
      result = fn(result, item);
    }

    return result;
  },
  (fn, array) => reduce(fn, array, undefined),
  (fn) => (array) => reduce(fn, array)
);

# Playlist