diff options
| author | Kai Stevenson <kai@kaistevenson.com> | 2025-11-09 21:08:12 -0800 |
|---|---|---|
| committer | Kai Stevenson <kai@kaistevenson.com> | 2025-11-09 21:08:30 -0800 |
| commit | 413eaa284e164143c5416cdce5a1de0f9f992409 (patch) | |
| tree | d999e8cbaddefcce9df3265c594083177427b6cb /src/lang/js-lang | |
| parent | 93992029bd349185d15de02e0f633e95c62695a9 (diff) | |
map + reduce
Diffstat (limited to 'src/lang/js-lang')
| -rw-r--r-- | src/lang/js-lang/builtin/sbuiltin.ts | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/lang/js-lang/builtin/sbuiltin.ts b/src/lang/js-lang/builtin/sbuiltin.ts index 013854c..7d9b851 100644 --- a/src/lang/js-lang/builtin/sbuiltin.ts +++ b/src/lang/js-lang/builtin/sbuiltin.ts @@ -40,6 +40,30 @@ export const V_SBUILTIN_Map: SBUILTIN = (node, frame) => { return values.map((v, i) => callFn(fn, [v, i], frame)); }; +export const V_SBUILTIN_Reduce: SBUILTIN = (node, frame) => { + const children = getEvaluatedChildren(node, frame); + const fn = children[1] as FnPrim | undefined; + const acc = children[2]; + + if (!fn?.fn) { + throw new Error( + `Invalid params for reduce: ${JSON.stringify(children, undefined, 2)}` + ); + } + + const values = children[0]; + + if (!Array.isArray(values)) { + // add to ts + throw new Error(`Can't reduce non-array value: ${values}`); + } + + return values.reduce( + (acc, cur, idx) => callFn(fn, [acc, cur, idx], frame), + acc + ); +}; + export const V_SBUILTIN_IfElse: SBUILTIN = (node, frame) => { const children = node.children; @@ -59,5 +83,6 @@ export const V_SBUILTIN_IfElse: SBUILTIN = (node, frame) => { export const nameToSBUILTIN: Record<string, SBUILTIN> = { call: V_SBUILTIN_Call, map: V_SBUILTIN_Map, + reduce: V_SBUILTIN_Reduce, "?": V_SBUILTIN_IfElse, }; |
