match.js
1.88 KB
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
/* jshint globalstrict: true */
/* global require */
/* global module */
"use strict";
function match(tokens, str) {
var curr, next, next_pos;
var p = 0;
while(tokens.length > 0) {
curr = tokens.shift();
if (curr[0] === 1) {
//the current token is a wildcard
next = tokens.shift();
if (next) {
/*
* there is also another token after it
* so we match for that with a prefix > 1 for the wildcard
*/
next_pos = str.indexOf(next[1]);
if (next_pos > 0) {
//move the pointer to the end of the non-wildcard token
p = next_pos + next[1].length;
} else {
//didn't fit. FAIL!
return false;
}
} else {
//the current wildcard token is also the last token.
if (str === "") {
//but there's nothing left to match. FAIL!
return false;
}
/*
* Since this last token is a wildcard.
* It uses up the rest of the string.
*/
str = "";
}
} else {
// the current token is a string token
if (str.indexOf(curr[1]) !== 0) {
// it doesn't fit at the beginning. FAIL!
return false;
} else {
// move pointer to the end of the string token
p = p + curr[1].length;
}
}
// cut the already matched part from the beginning of the string
str = str.substr(p);
}
if (str.length > 0) {
// the tokens didn't use up the
return false
}
// it did actually match. WOW!
return true;
}
module.exports = match;