From eec483093df7075cc94f686b1440f0dcfd76f466 Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Fri, 11 Jul 2025 18:37:47 -0300 Subject: src/sjs.mjs: Add reductions() --- src/sjs.mjs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/sjs.mjs b/src/sjs.mjs index 2c9d551..e9da7fc 100644 --- a/src/sjs.mjs +++ b/src/sjs.mjs @@ -294,9 +294,8 @@ export const reduced = x => new Reduced(x); const reduceRec = (coll, fn, acc, index) => isReduced(acc) ? acc.value : - index === coll.length - ? acc - : reduceRec( + index === coll.length ? acc : + reduceRec( coll, fn, fn(acc, coll[index], index, coll), @@ -308,6 +307,30 @@ export const reduce = (coll, fn, init) => ? reduceRec(coll.slice(1), fn, coll[0], 0) : reduceRec(coll, fn, init, 0); +const reductionsRec = (coll, fn, acc, index, steps) => { + if (isReduced(acc)) { + return steps.concat(acc.value); + } + + if (index === coll.length) { + return steps; + } + + const newAcc = fn(acc, coll[index], index, coll); + return reductionsRec( + coll, + fn, + newAcc, + index + 1, + steps.concat(newAcc), + ); +}; + +export const reductions = (coll, fn, init) => + init === undefined + ? reductionsRec(coll.slice(1), fn, coll[0], 0, [coll[0]]) + : reductionsRec(coll, fn, init, 0, []); + export const mapValues = (obj, fn) => Object.keys(obj).reduce( (o, k) => ({ -- cgit v1.2.3