forked from Fostecks/pepospin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.js
More file actions
109 lines (85 loc) · 2.22 KB
/
Copy pathtrie.js
File metadata and controls
109 lines (85 loc) · 2.22 KB
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
class Trie {
constructor(channels) {
this.root = {};
if (!channels) return;
for (let channel of channels) {
this.add(channel);
}
}
add(channel) {
let curr = this.root;
let chars = channel.split('');
for (let i = 0; i < chars.length; i++) {
let c = chars[i];
if (!curr[c]) {
curr[c] = {};
}
if (i == chars.length - 1) {
curr[c]['end'] = true;
break;
}
curr = curr[c];
}
}
remove(channel) {
let curr = this.root;
let chars = channel.split('');
let collapse = this._remove(chars, curr);
if (collapse) {
delete curr[Object.keys(curr)[0]];
}
}
_remove(chars, curr, collapse) {
let c = chars.shift();
curr = curr[c];
if (chars.length > 0) {
collapse = this._remove(chars, curr, collapse);
}
if (collapse === true) {
if (curr.end) {
return false;
}
delete curr[Object.keys(curr)[0]];
return true;
}
if (collapse === false) {
return false;
}
if (collapse === undefined) {
delete curr.end;
}
if (!collapse && Object.keys(curr).length === 0) {
return true;
} else {
return false;
}
}
find(prefix) {
let curr = this.root;
for (let x of prefix.split('')) {
if (!curr[x]) {
return [];
}
curr = curr[x];
}
return this._search(prefix, curr);
}
isEmpty() {
return Object.keys(this.root).length === 0;
}
_search(prefix, curr) {
let result = [];
let stack = [];
Object.keys(curr).forEach(e => stack.push(e));
while(stack.length > 0) {
let x = stack.pop();
if (x === 'end') {
result.push(prefix);
} else {
this._search(prefix + x, curr[x]).forEach(e => result.push(e));
}
}
return result;
}
}
module.exports = Trie;