-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrie.js
56 lines (45 loc) · 1.46 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
(function(){
function Trie() {
var root = new Node('');
this.addWord = function(word) {
var node = root;
for (var i = 0; i < word.length; i++) {
if (!node.children[word[i]]) {
node.children[word[i]] = new Node(word[i]);
}
node = node.children[word[i]];
}
node.terminator = true;
}
this.getWordsForPrefix = function(prefix) {
return walk(root, [], prefix, []);
function walk(node, stack, prefix, res) {
stack.push(node.value);
if (node.terminator) res.push(stack.slice().join(''));
if (node.children[prefix[0]]) {
walk(node.children[prefix[0]], stack, prefix.slice(1), res);
}
if (!prefix.length) {
for (var key in node.children) {
walk(node.children[key], stack.slice(), '', res);
}
}
return res;
}
}
}
function Node(value) {
this.value = value;
this.terminator = false;
this.children = {}
}
var root = this;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Trie;
}
exports.Trie = Trie;
} else {
root.Trie = Trie;
}
})();