-
Notifications
You must be signed in to change notification settings - Fork 8
/
trie.js
85 lines (76 loc) · 2.27 KB
/
trie.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function TrieNode(){
this.count = 0;
this.next = {};
this.exist = false;
this.insert = function(word){
let node = this;
for (let i of word){
// console.log(i, node.next)
if (! (i in node.next)){
node.next[i] = new TrieNode()
}
node = node.next[i];
node.count ++;
}
node.exist = true;
};
this.search = function(word, prefix){
let node = this;
for (let i of word){
node = node.next[i];
if (!node){
return false;
}
}
if(node.exist || prefix){
return node;
}else{
return false;
}
};
this.get_through = function(root, out, is_root){
let node = this;
for (let i in node.next){
let next_node = node.next[i];
if (is_root){
next_node.word = i;
next_node.get_through(root, out)
}else{
next_node.word = node.word.concat(i);
if (next_node.exist){
out[next_node.word] = next_node.count;
}
next_node.get_through(root, out)
}
}
node.word = '';
};
this.with_prefix = function(prefix, include_prefix){
let node = this.search(prefix, true);
if (node === false){
return node;
}else{
node.word = prefix;
let out = {};
if (include_prefix){
out[prefix] = node.count;
}
node.get_through(node, out, false);
return out
}
}
}
// var strings = ['But', 'it', 'also', 'shows', 'that', 'bilinguals', 'are', 'more', 'flexible', 'thinkers', 'append', 'already', 'it', 'iron', 'item'];
// var root = new TrieNode();
// for (let i of strings){
// root.insert(i)
// }
// console.log('search "thinker": ', root.search('thinker'));
// console.log('search "thinkers": ', root.search('thinkers'));
// console.log(root.with_prefix('it', true));
// console.log(root.with_prefix('it', false));
// var out = {};
// root.get_through(root, out, true);
// console.log(out);
// console.log('a');
module.exports = TrieNode