From 4f53f8998cbed82b0c04432b305c4a37caddd8e6 Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Thu, 9 Apr 2026 16:54:31 -0300 Subject: src/sjs.mjs: Loop for reduce to avoid stack overflows --- src/sjs.mjs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) (limited to 'src') 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) => - init === undefined - ? reduceRec(coll.slice(1), fn, coll[0], 0) - : reduceRec(coll, fn, init, 0); +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; +}; + const reductionsRec = (coll, fn, acc, index, steps) => { if (isReduced(acc)) { -- cgit v1.3