UNPKG

926 BJavaScriptView Raw
1export function reduce(source, optionsOrAccumulator, seed) {
2 const options =
3 // eslint-disable-next-line no-nested-ternary
4 typeof optionsOrAccumulator === 'function'
5 ? arguments.length > 2
6 ? { 'callback': optionsOrAccumulator, 'seed': seed }
7 : { 'callback': optionsOrAccumulator }
8 : optionsOrAccumulator;
9 const { ['seed']: _seed, ['callback']: callback } = options;
10 const hasSeed = options.hasOwnProperty('seed');
11 let i = 0;
12 let hasValue = false;
13 let acc = _seed;
14 for (const item of source) {
15 if (hasValue || (hasValue = hasSeed)) {
16 acc = callback(acc, item, i++);
17 }
18 else {
19 acc = item;
20 hasValue = true;
21 i++;
22 }
23 }
24 if (!(hasSeed || hasValue)) {
25 throw new Error('Sequence contains no elements');
26 }
27 return acc;
28}
29
30//# sourceMappingURL=reduce.mjs.map