Skip to content

Commit 011d0e4

Browse files
committed
Add basic suffix tree
1 parent aa667f1 commit 011d0e4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/data-structures/suffix-tree.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
function Node(value) {
2+
this.value = value;
3+
this.nodes = [];
4+
this.leaves = [];
5+
}
6+
7+
function SuffixTree() {
8+
this.root = new Node('');
9+
}
10+
11+
SuffixTree.prototype.addNode = (function () {
12+
13+
function addNode(suffix, current) {
14+
var n, l;
15+
for (var i = 0; i < current.nodes.length; i += 1) {
16+
n = current.nodes[i];
17+
if (n.value === suffix[0]) {
18+
addNode(suffix.substr(1, suffix.length), n);
19+
return;
20+
}
21+
}
22+
for (i = 0; i < current.leaves.length; i += 1) {
23+
l = current.leaves[i];
24+
if (l[0] === suffix[0]) {
25+
var prefix = l[0];
26+
n = new Node(prefix);
27+
current.nodes.push(n);
28+
current.leaves.splice(current.leaves.indexOf(l), 1);
29+
l = l.substr(1, l.length);
30+
suffix = suffix.substr(1, suffix.length);
31+
addNode(l, n);
32+
addNode(suffix, n);
33+
return;
34+
}
35+
}
36+
current.leaves.push(suffix);
37+
}
38+
39+
return function (suffix) {
40+
addNode(suffix, this.root);
41+
};
42+
}());
43+
44+
SuffixTree.prototype.build = function (string) {
45+
for (var i = 0; i < string.length; i += 1) {
46+
this.addNode(string.substr(i, string.length));
47+
}
48+
};
49+
50+
// var suffix = new SuffixTree();
51+
// suffix.build('banana');
52+
// console.log(suffix);

0 commit comments

Comments
 (0)