1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
type BUILTIN = (args: any[]) => any;
export const V_BUILTIN_Arr: BUILTIN = (args) => args;
// FIXME actually implement this properly
export const V_BUILTIN_ToString: BUILTIN = (args) =>
args.length === 1 ? JSON.stringify(args[0]) : JSON.stringify(args);
export const V_BUILTIN_Add: BUILTIN = (args) => {
if (args.every((arg) => ["string", "number"].includes(typeof arg))) {
return args.reduce(
(acc, cur) => acc + cur,
typeof args[0] === "string" ? "" : 0
);
}
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);
}
throw new Error(
`Can only multiply [number, number], but got ${JSON.stringify(
args,
undefined,
2
)}`
);
};
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) {
last = arg;
continue;
}
if (arg === last) {
last = arg;
continue;
}
return false;
}
return true;
};
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,
};
|