-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmath.test.ts
75 lines (65 loc) · 1.75 KB
/
math.test.ts
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
import { afterEach, beforeEach, describe, expect, it } from "./test-deps.ts";
import { has, hasMore, parse, ParseGenerator } from "./index.ts";
describe("math parser", () => {
const whitespaceMay = /^\s*/;
function* ParseInt() {
const isNegative: boolean = yield has("-");
const [stringValue]: [string] = yield /^\d+/;
return parseInt(stringValue, 10) * (isNegative ? -1 : 1);
}
type Operator = "+" | "-" | "*" | "/";
function* ParseOperator() {
const operator: Operator = yield ["+", "-", "*", "/"];
return operator;
}
function applyOperator(a: number, b: number, operator: Operator): number {
switch (operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
}
function* MathExpression(): ParseGenerator {
yield whitespaceMay;
let current: number = yield ParseInt;
while (yield hasMore) {
yield whitespaceMay;
const operator: Operator = yield ParseOperator;
yield whitespaceMay;
const other = yield ParseInt;
current = applyOperator(current, other, operator);
}
return current;
}
Deno.test("many", () => {
([
["1 + 1", 2],
["1 + 2", 3],
["2 + 2", 4],
["21 + 19", 40],
["21 + -19", 2],
["-21 + 19", -2],
["-21 + -19", -40],
["0 - 10", -10],
["21 - 19", 2],
["-21 - 19", -40],
["1 * 1", 1],
["2 * 2", 4],
["12 * 12", 144],
["1 / 2", 0.5],
["10 / 2", 5],
["10 / 20", 0.5],
] as const).forEach(([input, output]) => {
expect(parse(input, MathExpression())).toEqual({
success: true,
result: output,
remaining: "",
});
});
});
});