-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtritium.js
132 lines (108 loc) · 2.88 KB
/
tritium.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
var ternarySearchTree = function() {
var root,
numWords = 0,
numNodes = 0;
function insert(node, chars) {
var firstChar = chars.charAt(0),
node;
if (!firstChar) return null;
if (!node) {
node = {
character: firstChar,
left: null,
middle: null,
right: null,
word: false
};
numNodes += 1;
}
if (!root) root = node;
if (firstChar < node.character) {
node.left = insert(node.left, chars);
} else if (firstChar === node.character) {
if (chars.length > 1) {
node.middle = insert(node.middle, chars.slice(1));
} else {
node.word = true;
numWords += 1;
}
} else {
node.right = insert(node.right, chars);
}
return node;
}
function search(node, chars) {
var firstChar = chars.charAt(0),
rest;
if (!node || !firstChar) return null;
if (firstChar < node.character) {
return search(node.left, chars);
} else if (firstChar > node.character) {
return search(node.right, chars);
} else {
rest = chars.slice(1);
if (!rest) {
return node;
} else {
return search(node.middle, rest);
}
}
return null;
}
function childWords(node, prefix, limit) {
var foundWords = [],
parentNode,
traversalData = {
foundWords: foundWords,
prefix: prefix
};
if (!node || !prefix) return foundWords;
parentNode = search(node, prefix);
if (!parentNode) return foundWords;
depthFirstTraversal(parentNode.middle, function(node, data) {
if (data.foundWords.length >= limit) return null;
data = {
foundWords: data.foundWords,
prefix: data.prefix + node.character
};
if (node.word) data.foundWords.push(data.prefix);
return data;
}, traversalData);
return foundWords;
}
function depthFirstTraversal(node, visit, data) {
var modifiedData;
if (!node || data === null) return;
if (node.left) depthFirstTraversal(node.left, visit, data);
modifiedData = visit(node, data);
if (node.middle) depthFirstTraversal(node.middle, visit, modifiedData);
if (node.right) depthFirstTraversal(node.right, visit, data);
}
return {
getRoot: function() {
return root;
},
wordCount: function() {
return numWords;
},
nodeCount: function() {
return numNodes;
},
add: function(word) {
insert(root, word);
},
has: function(prefix, isWord) {
var foundNode = search(root, prefix);
return foundNode
? isWord ? foundNode.word : true
: false;
},
prefixSearch: function(prefix, limit) {
return childWords(root, prefix, limit);
},
traverse: function(visit, data) {
depthFirstTraversal(root, visit, data);
}
}
};
exports.ternarySearchTree = ternarySearchTree;