-
Notifications
You must be signed in to change notification settings - Fork 1
/
triematch.js
49 lines (45 loc) · 1.22 KB
/
triematch.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
class TrieMatch{
//puclic
chars = {};
value;
constructor(arr){
if(arr){
for(let i = 0; i < arr.length; i++){
this.insert(arr[i],arr[i]);
}
}
}
insert(word,content){
if(word === ""){
this.value = content;
return false;
}
let chars = this.chars;
let char = word[0];
if(!(char in chars))chars[char] = new TrieMatch();
chars[char].insert(word.slice(1),content);
}
contains(word){// bool
if(word === "" && this.value)return true;
let chars = this.chars;
let char = word[0];
if(!(char in chars))return false;
return chars[char].contains(word.slice(1));
}
maxMatch(str,i){// [word, i1]
if(i === str.length){
return [this.value || "",i];
}else if(i >= str.length){
throw new Error("string out of range, in a trie operation");
}
let chars = this.chars;
let char = str[i];
if(char in chars){
let result;
return chars[char].maxMatch(str,i+1);
}else{
return [this.value || "",i];
}
}
};
module.exports = TrieMatch;