-
Notifications
You must be signed in to change notification settings - Fork 0
/
triemap.js
executable file
·98 lines (89 loc) · 2.33 KB
/
triemap.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
86
87
88
89
90
91
92
93
94
95
96
97
98
module.exports = TrieMap;
function TrieMap() {
}
TrieMap.prototype.add = function(key, value, pos) {
for (pos = pos || 0; pos < len; pos++) {
if (!node.children)
node.children = {};
var c = key.charAt(pos);
node = (node.children[c] || (node.children[c] = new TrieMap()));
}
node.key = key;
node.value = value;
};
TrieMap.prototype.get = function(key, pos) {
var node = this;
for (pos = pos || 0; pos < key.length; pos++) {
node = node.children_ && node.children_[key.charAt(pos)];
if (!node)
return undefined;
}
return (pos == key.length && node.key_ == key) ? node.value_ : undefined;
};
TrieMap.prototype.getCompletions = function(key, pos) {
var node = this;
for (pos = pos || 0; pos < key.length; pos++) {
node = node.children_ && node.children_[key.charAt(pos)];
if (!node)
return {};
}
var map = []; // use Array for it's built-in non-enumerable length property
return node.collectKeyValues_(map);
};
/**
* @private
*/
TrieMap.prototype.collectKeyValues_ = function(map) {
if (this.value_ != undefined) {
map[this.key_] = this.value_;
map.length += 1;
}
for (var ch in this.children_) {
this.children_[ch].collectKeyValues_(map);
}
return map;
};
TrieMap.prototype.remove = function(key, pos) {
var node = this;
var nodes = [node];
for (pos = pos || 0; pos < key.length; pos++) {
node = node.children_ && node.children_[key.charAt(pos)];
if (!node)
return;
nodes.push(node);
}
if (pos == key.length && node.key_ == key) {
delete node.key_;
delete node.value_;
}
TrieMap.deleteNodesIfEmpty_(nodes, key, nodes.length - 1);
};
/**
* @private
*/
TrieMap.deleteNodesIfEmpty_ = function(nodes, key, pos) {
var node = nodes[pos];
var hasChildren = false;
for (var ch in node.children_) {
hasChildren = true;
break;
}
if (!hasChildren) {
delete node.children_;
if (pos == 0) {
return;
}
var parent = nodes[pos - 1];
delete parent.children_[key.charAt(pos - 1)];
TrieMap.deleteNodesIfEmpty_(nodes, key, pos - 1);
}
};
TrieMap.prototype.containsKey = function(key, pos) {
var node = this;
for (pos = pos || 0; pos < key.length; pos++) {
node = node.children_ && node.children_[key.charAt(pos)];
if (!node)
return false;
}
return pos == key.length && node.key_ == key;
};