-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathevaluator.ts
More file actions
105 lines (90 loc) · 2.34 KB
/
evaluator.ts
File metadata and controls
105 lines (90 loc) · 2.34 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import type { Node } from './parser.ts';
export type Func = (...args: number[]) => number;
export const defaultFuncs: Record<string, Func> = {
// Comparison
min: Math.min,
max: Math.max,
clamp: (lo, v, hi) => Math.min(Math.max(v, lo), hi),
// Sign / absolute value
abs: Math.abs,
sign: Math.sign,
// Exponential
pow: Math.pow,
sqrt: Math.sqrt,
hypot: Math.hypot,
log: Math.log,
exp: Math.exp,
// Trig (radians)
sin: Math.sin,
cos: Math.cos,
tan: Math.tan,
asin: Math.asin,
acos: Math.acos,
atan: Math.atan,
atan2: Math.atan2,
// Stepped value
round: Math.round,
floor: Math.floor,
ceil: Math.ceil,
trunc: Math.trunc,
// Floor-mod (result sign follows divisor); `rem` uses JS `%` (sign follows dividend).
mod: (a, b) => ((a % b) + b) % b,
rem: (a, b) => a % b,
};
export const defaultConsts: Record<string, number> = {
pi: Math.PI,
e: Math.E,
infinity: Infinity,
};
export interface EvalContext {
funcs?: Record<string, Func>;
consts?: Record<string, number>;
}
export function evaluate(node: Node, ctx: EvalContext = {}): number {
const funcs = ctx.funcs ?? defaultFuncs;
const consts = ctx.consts ?? defaultConsts;
switch (node.type) {
case 'Num':
return node.value;
case 'Dim':
throw new Error(
`Cannot evaluate dimension ${node.value}${node.unit} as a plain number`
);
case 'Ident': {
const v = consts[node.name.toLowerCase()];
if (v === undefined) {
throw new Error(`Unknown identifier "${node.name}"`);
}
return v;
}
case 'Unary': {
const v = evaluate(node.arg, { funcs, consts });
return node.op === '-' ? -v : +v;
}
case 'Binary': {
const l = evaluate(node.left, { funcs, consts });
const r = evaluate(node.right, { funcs, consts });
switch (node.op) {
case '+':
return l + r;
case '-':
return l - r;
case '*':
return l * r;
case '/':
if (r === 0) {
throw new Error('Division by zero');
}
return l / r;
}
}
case 'Call': {
const fn = funcs[node.name.toLowerCase()];
if (!fn) {
throw new Error(`Unknown function "${node.name}"`);
}
const args = node.args.map((a) => evaluate(a, { funcs, consts }));
return fn(...args);
}
}
}