summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2026-04-09 16:54:31 -0300
committerEuAndreh <eu@euandre.org>2026-04-09 16:54:31 -0300
commit4f53f8998cbed82b0c04432b305c4a37caddd8e6 (patch)
tree9f4d758a0c6acffe19a2f608688d8136f9f337a0 /src
parentMakefile: Align ending backslack (diff)
downloadsjs-4f53f8998cbed82b0c04432b305c4a37caddd8e6.tar.gz
sjs-4f53f8998cbed82b0c04432b305c4a37caddd8e6.tar.xz
src/sjs.mjs: Loop for reduce to avoid stack overflowsHEADmain
Diffstat (limited to 'src')
-rw-r--r--src/sjs.mjs22
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)) {