-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (82 loc) · 2.16 KB
/
index.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
'use strict';
/**
* @param {string[]} data - List of values to add initially
* @param {Object} options - Config options
* @param {string} options.delimiter - Delimiter for breaking up values
*/
function Trie(data) {
data = data || []
this.root = { children: {}, isFlagged: false };
data.forEach(val => this.add(val));
}
/**
* @param {string} value - Value to add
* @returns {Trie} Same instance of Trie for chaining
*/
Trie.prototype.add = function(value) {
let current = this.root;
for (let piece of value) {
if (!current.children[piece]) {
current.children[piece] = { children: {}, isFlagged: false };
}
current = current.children[piece];
}
current.isFlagged = true;
return this;
};
/**
* @param {string} value - Value to remove
* @return {Trie} Same instance of Trie for chaining
*/
Trie.prototype.remove = function(value) {
let current = this.root;
const hierarchy = [current];
const words = [];
for (let piece of value) {
words.unshift(piece);
if (!current.children[piece]) {
return this;
}
current = current.children[piece];
hierarchy.unshift(current);
}
current.isFlagged = false;
for (let j = 0; j < hierarchy.length; j++) {
if (Object.keys(hierarchy[j].children).length > 0 || hierarchy[j].isFlagged) {
break;
}
if (j + 1 < hierarchy.length) {
delete hierarchy[j + 1].children[words[j]];
}
}
return this;
};
/**
* @param {string} value - Value to test for presence of
* @return {Boolean} True if the value exists
*/
Trie.prototype.lookup = function(value) {
let current = this.root;
for (let piece of value) {
if (!current.children[piece]) {
return false;
}
current = current.children[piece];
}
return current.isFlagged;
};
/**
* @param {string} value - Value to test for being a isPrefix
* @return {Boolean} True if the value is a prefix
*/
Trie.prototype.isPrefix = function(value) {
let current = this.root;
for (let piece of value) {
if (!current.children[piece]) {
return false;
}
current = current.children[piece];
}
return Object.keys(current.children).length > 0;
};
module.exports = Trie;