-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
69 lines (60 loc) · 1.38 KB
/
calculator.js
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
import {
createParser,
setParser,
regex,
seq,
rep,
alt,
ch,
end,
using
} from "../dist/parser";
let Term = createParser();
let Factor = createParser();
let Exp = createParser();
let Parser = createParser();
function passBracket(result) {
return result.map(resultItem => {
const [, exp, , ...rest] = resultItem;
return [exp].concat(rest);
});
}
const calculatorMap = {
"+": function(left, right) {
return parseInt(left) + parseInt(right);
},
"-": function(left, right) {
return parseInt(left) - parseInt(right);
},
"*": function(left, right) {
return parseInt(left) * parseInt(right);
},
"/": function(left, right) {
return parseInt(left) / parseInt(right);
}
};
let calculator = result => {
return result.map(resultItem => {
if (resultItem.length < 3) {
return resultItem;
}
const [left, operator, right, ...rest] = resultItem;
return [`${calculatorMap[operator](left, right)}`].concat(rest);
});
};
setParser(
Term,
alt(regex("\\d+(\\.\\d+)?"), using(seq(ch("("), Exp, ch(")")), passBracket))
);
setParser(
Factor,
using(seq(Term, rep(seq(alt(ch("*"), ch("/")), Term))), calculator)
);
setParser(
Exp,
using(seq(Factor, rep(seq(alt(ch("+"), ch("-")), Factor))), calculator)
);
setParser(Parser, seq(Exp, end()));
for (const result of Parser[0]("123+321*(456+654)")) {
console.log("RESULT :", result);
}