diff options
| author | Kai Stevenson <kai@kaistevenson.com> | 2025-11-05 01:20:07 -0800 |
|---|---|---|
| committer | Kai Stevenson <kai@kaistevenson.com> | 2025-11-06 20:28:00 -0800 |
| commit | d8a969e231135978c4dd1fa67559101f506ad6f3 (patch) | |
| tree | 7a556db33abe541fa3f5902690ca93d782c0ecc7 /src/lang/js-lang/builtin | |
| parent | e86c68dffaffee6ba44d98ba06761245f6d5b670 (diff) | |
recursion works for types with depth limit 5
Diffstat (limited to 'src/lang/js-lang/builtin')
| -rw-r--r-- | src/lang/js-lang/builtin/builtin.ts | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/lang/js-lang/builtin/builtin.ts b/src/lang/js-lang/builtin/builtin.ts index d54c439..ed279f6 100644 --- a/src/lang/js-lang/builtin/builtin.ts +++ b/src/lang/js-lang/builtin/builtin.ts @@ -17,6 +17,22 @@ export const V_BUILTIN_Add: BUILTIN = (args) => { throw new Error(`Cannot add operands ${JSON.stringify(args, undefined, 2)}`); }; +export const V_BUILTIN_Sub: BUILTIN = (args) => { + if (args.length !== 2) { + throw new Error( + `Can only sub [number, number], but got ${JSON.stringify(args)}` + ); + } + + if (isNaN(args[0]) || isNaN(args[1])) { + throw new Error( + `Can only sub [number, number], but got ${JSON.stringify(args)}` + ); + } + + return args[0] - args[1]; +}; + export const V_BUILTIN_Mul: BUILTIN = (args) => { if (args.every((arg) => typeof arg === "number") && args.length === 2) { return args.reduce((acc, cur) => acc * cur, 1); @@ -31,6 +47,33 @@ export const V_BUILTIN_Mul: BUILTIN = (args) => { ); }; +export const V_BUILTIN_Eq: BUILTIN = (args) => { + const firstLast = {}; + let last = firstLast; + + for (const arg of args) { + if (!["number", "string", "boolean"].includes(typeof arg)) { + throw new Error( + `Can only check equality of numbers or string or boolean, but got ${JSON.stringify( + args + )}` + ); + } + + if (last === firstLast) { + continue; + } + + if (arg === last) { + continue; + } + + return false; + } + + return true; +}; + export const V_BUILTIN_IfElse: BUILTIN = (args) => { if (args.length !== 3) { throw new Error(`Invalid args for "if": ${JSON.stringify(args)}`); @@ -49,6 +92,8 @@ export const nameToBUILTIN: Record<string, BUILTIN> = { arr: V_BUILTIN_Arr, tostring: V_BUILTIN_ToString, add: V_BUILTIN_Add, + sub: V_BUILTIN_Sub, mul: V_BUILTIN_Mul, + eq: V_BUILTIN_Eq, "?": V_BUILTIN_IfElse, }; |
