-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.js
34 lines (34 loc) · 837 Bytes
/
parse.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
var Parser = function (tokens) {
this.tokens = tokens;
this.lookahead = this.tokens.shift();
};
Parser.prototype.expr = function () {
this.term();
while (true) {
if (this.lookahead == '+' ) {
this.match('+');
this.term();
console.log('+');
} else if (this.lookahead == '-' ) {
this.match('-');
this.term();
console.log('-');
} else {
return;
}
}
};
Parser.prototype.term = function () {
if ('0123456789'.indexOf(this.lookahead) >= 0) {
console.log(this.lookahead);
return this.match(this.lookahead);
}
throw new Error('syntax error');
};
Parser.prototype.match = function (matcher) {
if (this.lookahead === matcher) {
return this.lookahead = this.tokens.shift();
}
throw new Error('syntax error');
};
new Parser('1+1+2-1+5-2'.split('')).expr();