diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/sjs.mjs | 22 |
1 files changed, 9 insertions, 13 deletions
diff --git a/src/sjs.mjs b/src/sjs.mjs index aae85a7..aafd7ba 100644 --- a/src/sjs.mjs +++ b/src/sjs.mjs @@ -292,20 +292,16 @@ export const isReduced = x => x instanceof Reduced; export const reduced = x => new Reduced(x); -const reduceRec = (coll, fn, acc, index) => - isReduced(acc) ? acc.value : - index === coll.length ? acc : - reduceRec( - coll, - fn, - fn(acc, coll[index], index, coll), - index + 1, - ); +export const reduce = (coll, fn, init) => { + let acc = init === undefined ? coll[0] : init; + let start = init === undefined ? 1 : 0; + for (let i = start; i < coll.length; i++) { + acc = fn(acc, coll[i], i, coll); + if (isReduced(acc)) return acc.value; + } + return acc; +}; -export const reduce = (coll, fn, init) => - init === undefined - ? reduceRec(coll.slice(1), fn, coll[0], 0) - : reduceRec(coll, fn, init, 0); const reductionsRec = (coll, fn, acc, index, steps) => { if (isReduced(acc)) { |
