-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.js
60 lines (54 loc) · 1.49 KB
/
parser.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
const Parser = (() => {
class Cursor {
constructor(iterable, index, length){
this.index = index || 0;
this.iterable = interable;
this.length = length == undefined
? iterable.length - this.index
: length;
}
head(){
return this.iterable[this.index];
}
move(distance){
return new Cursor(this.iterable, this.index + distance, this.length - distance);
}
}
class ParseResult {
constructor(value, rest, success){
this.value = value;
this.rest = rest;
this.success = success;
}
map(func){
if(this.success){
return new Success(func(this.value), this.rest, true);
} else {
return this;
}
}
chain(func){
if(success){
return func(this.value, this.rest, true);
} else {
return this;
}
}
}
class Parser {
//(string => ParseResult) => ()
constructor(parseFunc){
this.parseFunc = parseFunc;
}
parse(value){
if(value instanceof Cursor){
return this.parseFunc(value);
} else {
return this.parseFunc(new Cursor(value));
}
}
map(func){
return new Parser(cursor => this.parseFunc(cursor).map(func))
}
}
})();