UNPKG

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