-
-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathtrie.js
More file actions
466 lines (429 loc) · 14.1 KB
/
trie.js
File metadata and controls
466 lines (429 loc) · 14.1 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { isString, isNonEmptyString } from '../common/strings.js';
import { isUndefined } from '../common/basic.js';
import { ERROR_MSG_PARAM_TYPE } from '../common/errors.js';
const _root = new WeakMap();
const _size = new WeakMap();
const _value = new WeakMap();
const ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING = (fname, val, pname = 'key') => `Illegal argument for ${fname}: ${pname} = ${val} must be a non-empty string`;
/**
* @class Trie
*
* External API for a trie.
* Strings can be stored and optionally associated with values.
*/
class Trie {
constructor() {
_root.set(this, new TrieNode());
}
/**
* @name put
* @for Trie
* @description
* Store a key-value pair into the trie.
*
* @param {!string} key A non empty-string.
* @param {?*} val Optionally, a value can be associated with the key. Can be any value but `undefined`.
* By default, `null` is used.
* @returns {Trie} The trie itself, to allow method chaining.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
put(key, val = null) {
if (!isNonEmptyString(key)) {
throw new TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING('put', key));
}
_root.get(this).put(key, val);
return this;
}
/**
* @name get
* @for Trie
* @description
* Return the value associated with the key passed, if it is stored in the trie. Otherwise, on miss, it returns `undefined`.
*
* @param {!string} key A non empty-string.
* @returns {Trie} The value associated with the key, or undefined, if the key it's not stored on the trie.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
get(key) {
if (!isNonEmptyString(key)) {
throw new TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING('get', key));
}
return _root.get(this).get(key);
}
/**
* @name delete
* @for Trie
* @description
* Remove the key (and its value) from the trie.
*
* @param {!string} key A non empty-string.
* @returns {boolean} true iff the key was successfully deleted from the tree, false if it wan't found or an error happened.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
delete(key) {
if (!isNonEmptyString(key)) {
throw new TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING('delete', key));
}
return _root.get(this).delete(key)[0];
}
/**
* @name contains
* @for Trie
* @description
* Check if the given key is stored in the trie.
*
* @param {!string} key A non empty-string.
* @returns {boolean} true iff the key is currently stored in the trie.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
contains(key) {
if (!isNonEmptyString(key)) {
throw new TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING('contains', key));
}
return _root.get(this).contains(key);
}
/**
* @name isEmpty
* @for Trie
* @description
* Check if the trie is empty.
*
* @returns {boolean}
*/
isEmpty() {
return this.size === 0;
}
/**
* @name size
* @for Trie
* @getter
* @description
* The number of keys currently stored in the trie.
*
* @returns {number}
*/
get size() {
return _root.get(this).size;
}
/**
* @name longestPrefixOf
* @for Trie
* @description
* Search the trie for the longest key that is a prefix of s.
*
* @param {!string} s A non empty-string.
* @returns {string} The (possibly empty) longest prefix of key stored in the trie.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
longestPrefixOf(s) {
if (!isNonEmptyString(s)) {
throw new TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING('longestPrefixOf', s, 's'));
}
return _root.get(this).longestPrefixOf(s) || '';
}
/**
* @name keysWithPrefix
* @for Trie
* @description
* Search the trie for all the keys for which the s is a valid prefix.
*
* @param {!string} s A string, possibly empty.
* @returns {Generator<string>} all the keys having s as a prefix
* @throws {TypeError(ERROR_MSG_PARAM_TYPE)} If the argumentis not a string.
*/
*keysWithPrefix(s) {
if (!isString(s)) {
throw new TypeError(ERROR_MSG_PARAM_TYPE('keysWithPrefix', 's', s, 'string'));
}
let prefixNode = _root.get(this).getNode(s);
if (!isUndefined(prefixNode)) {
yield* prefixNode.keys([s]);
}
}
/**
* @name keys
* @for Trie
* @description
* Iterates through all the keys in the trie.
*
* @returns {Generator<string>} all the keys in the trie.
*/
*keys() {
yield* _root.get(this).keys();
}
/**
* @name items
* @for Trie
* @description
* Iterates through all the keys in the trie, returning for each one of them the pair [key, value].
* Note: you should use array destructuring to retrieve them.
*
* @returns {Generator<string, *>} all the (key, value) pairs in the trie.
*/
*items() {
yield* _root.get(this).items();
}
/**
* Iterator - so trie can be used in for... of loops.
*/
*[Symbol.iterator]() {
yield* this.items();
}
}
/**
* @class TrieNode
* @private
*
* Internal representation of a Trie.
* Each node is in practice the root of its sub-trie.
* It provides protected methods to search the trie and add new key-value pairs.
* For most operations, along with a string for the key to be searched/deleted/inserted, an index is passed, to mark the
* next character in the key that should be acted upon, rather than passing a substring with the first character removed.
* For example, get('ab' will make a recursive call to get('ab', 1), instead that a call to get('b').
* This is an optimization that allows keeping the asymptotic time required for each operation linear in the length of key.
* Otherwise, as strings are immutable, creating a substring with just one less character than the original one is a linear
* operation in the number of character copied, and a successful search would require n-1 + n-2 + n-3 + ... + 1 characters
* copied, for a total of n*(n-1)/2 - hence, the running time would be quadratic in the length of the string.
*/
class TrieNode {
/**
* @constructor
* @invariant key.length >= 0 && keyIndex <= key.length
*
* @param {?string} key The (possibly empty) string to be stored in the trie. Defaults to ''.
* @param {!*} value The value to be associated with the key. Defaults to undefined.
* @param {?number} keyIndex The index at which starts the substring of key to be stored in this subtrie.
*/
constructor(key = '', value = undefined, keyIndex = 0) {
this.links = {};
if (keyIndex === key.length) {
_size.set(this, 0);
this.value = value;
} else {
_size.set(this, 1);
this.links[key[keyIndex]] = new TrieNode(key, value, keyIndex + 1);
}
}
/**
* @name size
* @getter
* @description
* Getter for the size of the trie.
*
* @returns {number} The size of this subtrie.
*/
get size() {
return _size.get(this);
}
/**
* @name value
* @getter
* @description
* Getter for the value of the trie.
*
* @returns {*} The value stored in this node.
*/
get value() {
return _value.get(this);
}
/**
* @name value
* @setter
* @description
* Setter for the value of the trie.
*
* @param {!*} val The value to store in the node.
*/
set value(val) {
_value.set(this, val);
}
/**
* @name put
* @for TrieNode
* @description
* Store a key-value pair into the trie.
* @invariant key.length >= 0 && keyIndex <= key.length
*
* @param {!string} key A non empty-string.
* @param {?*} value Can be any value but `undefined`.
* @param {?number} keyIndex The index at which starts the substring of key to be stored in this subtrie.
* @returns {boolean} true unless the key was already in the trie and got updated.
* @throws {TypeError(ERROR_MSG_PARAM_KEY_NON_EMPTY_STRING)} If the argument is not a non-empty string.
*/
put(key, value, keyIndex = 0) {
let isNewKey;
if (keyIndex === key.length) {
isNewKey = isUndefined(this.value);
this.value = value;
} else {
let next = key[keyIndex];
if (this.links.hasOwnProperty(next)) {
isNewKey = this.links[next].put(key, value, keyIndex + 1);
if (isNewKey) {
_size.set(this, this.size + 1);
}
} else {
_size.set(this, this.size + 1);
this.links[next] = new TrieNode(key, value, keyIndex + 1);
isNewKey = true;
}
}
return isNewKey;
}
/**
* @name get
* @for TrieNode
* @description
* Return the value associated with the key passed, if it is stored in the subtrie. Otherwise, on miss, it returns `undefined`.
* @invariant key.length >= 0 && keyIndex <= key.length
*
* @param {?string} key The (possibly empty) string to be looked for in the trie.
* @param {?number} keyIndex The index at which starts the substring of key to be looked for in this subtrie.
* @return {*} The value associated with the key, or undefined in the key isn't stored on the trie.
*/
get(key, keyIndex = 0) {
let node = this.getNode(key, keyIndex);
return node && node.value;
}
/**
* @name getNode
* @for TrieNode
* @description
* Return the node associated with the key passed, if it is stored in the subtrie. Otherwise, on miss, it returns `undefined`.
* @invariant key.length >= 0 && keyIndex <= key.length
*
* @param {?string} key The (possibly empty) string to be looked for in the trie.
* @param {?number} keyIndex The index at which starts the substring of key to be looked for in this subtrie.
* @return {TrieNode|undefined} The value associated with the key, or undefined in the key isn't stored on the trie.
*/
getNode(key, keyIndex = 0) {
let result;
if (keyIndex === key.length) {
result = this;
} else {
let next = key[keyIndex];
if (this.links.hasOwnProperty(next)) {
result = this.links[next].getNode(key, keyIndex + 1);
}
}
return result;
}
/**
* @name contains
* @for TrieNode
* @description
* Check if the given key is stored in the trie.
*
* @param {?string} key The (possibly empty) string to be looked for in the subtrie.
* @returns {boolean} true iff the key is currently stored in the trie.
*/
contains(key) {
return !isUndefined(this.get(key));
}
/**
* @name delete
* @for TrieNode
* @description
* Remove the key (and its value) from the subtrie.
* if all the links in the deleted node are null, we need to remove the node from the data structure. If doing so
* leaves all the links null in its parent, we need to remove that node, and so forth.
*
* @param {!string} key A non empty-string.
* @param {?number} keyIndex The index at which starts the substring of key contained in this subtrie.
* @returns {[boolean, boolean]} The first boolean is true iff the key was successfully deleted from the tree,
* false if it wan't found or an error happened.
* The second one is true iff the node doesn't have any child anymore.
*/
delete(key, keyIndex = 0) {
let [deleted, empty] = [false, false];
if (keyIndex === key.length) {
deleted = !isUndefined(this.value);
if (deleted) {
this.value = undefined;
if (this.size === 0) {
empty = true;
}
}
} else {
let next = key[keyIndex];
if (this.links.hasOwnProperty(next)) {
[deleted, empty] = this.links[next].delete(key, keyIndex + 1);
if (deleted) {
_size.set(this, this.size - 1);
}
if (empty) {
delete this.links[next];
empty = this.size === 0 && isUndefined(this.value);
}
}
}
return [deleted, empty];
}
/**
* @name longestPrefixOf
* @for TrieNode
* @description
* Return the longest prefix of the input s associated with the key passed, if it is stored in the subtrie. Otherwise, on miss, it returns `undefined`.
* @invariant s.length >= 0 && sIndex <= s.length
*
* @param {?string} s The (possibly empty) prefix to be looked for in the trie.
* @param {?number} sIndex The index at which starts the substring of string to be looked for in this subtrie.
* @return {*} The value associated with the key, or undefined in the key isn't stored on the trie.
*/
longestPrefixOf(s, sIndex = 0) {
let result;
if (sIndex === s.length) {
if (!isUndefined(this.value)) {
result = s;
}
} else {
let next = s[sIndex];
if (this.links.hasOwnProperty(next)) {
result = this.links[next].longestPrefixOf(s, sIndex + 1);
if (isUndefined(result) && !isUndefined(this.value)) {
result = s.substr(0, sIndex);
}
}
}
return result;
}
/**
* @name items
* @for TrieNode
* @description
* Iterate through all the key-value pairs stored in the trie.
*
* @param {?Array<string>} path The array of characters found in a path from the root of the trie to this node.
* Merging the array will give the key for current node.
* @returns {Generator<string, *>} all the (key, value) pairs in the subtrie.
*/
*items(path = []) {
if (!isUndefined(this.value)) {
yield {
key: path.join(''),
value: this.value
};
}
for (let c of Object.keys(this.links).sort()) {
path.push(c);
yield* this.links[c].items(path);
path.pop();
}
}
/**
* @name keys
* @for TrieNode
* @description
* Iterate through all the keys pairs stored in the trie.
*
* @param {?Array<string>} path The array of characters found in a path from the root of the trie to this node.
* Merging the array will give the key for current node.
* @returns {Generator<string>} all the keys in this subtrie.
*/
*keys(path = []) {
for (let { key, _ } of this.items(path)) {
yield key;
}
}
}
export default Trie;