-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringMatcher.js
55 lines (45 loc) · 1.3 KB
/
stringMatcher.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
function StringMatcher(inputString) {
this.inputString = inputString;
this.nextCharIndex = 0;
this.lastMatch = {start: -1, length: -1};
return this;
}
StringMatcher.prototype.read = function () {
return this.inputString[this.nextCharIndex++];
};
StringMatcher.prototype.peek = function () {
return this.inputString[this.nextCharIndex];
};
StringMatcher.prototype.end = function () {
return this.nextCharIndex >= this.inputString.length;
};
StringMatcher.prototype.remaining = function () {
return this.inputString.substring(this.nextCharIndex);
};
StringMatcher.prototype.getCharAt = function (index) {
return this.inputString[index];
};
StringMatcher.prototype.thenMatch = function (patternString) {
this.lastMatch.start = this.nextCharIndex;
this.lastMatch.length = 0;
var pattern = new StringMatcher(patternString);
while(!this.end() && !pattern.end() && this.peek() === pattern.peek()) {
this.lastMatch.length++;
this.read();
pattern.read();
}
if(pattern.end() && this.end()) {
this.lastMatch.type = 'fullMatch';
}
if(pattern.end() && !this.end()) {
this.lastMatch.type = 'endOfPattern';
}
if(!pattern.end() && this.end()) {
this.lastMatch.type = 'endOfStream';
}
if(!pattern.end() && !this.end()) {
this.lastMatch.type = 'mismatch';
}
return this;
};
module.exports = StringMatcher;