-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.js
78 lines (55 loc) · 1.51 KB
/
trie.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
/*
* Author: Alex Vanyan ([email protected])
* Data Structure: TRIE / Prefix Tree / Digital Tree
* Description: Example of finding URL in big array of URLs and returning a boolean value if it exists.
*/
class Trie {
constructor(bigData) {
this._prefixTree = {};
this._data = bigData;
this._build();
}
get tree() {
return this._prefixTree;
}
_addData(tree, charArr) {
const letter = charArr.shift();
if (!(letter in tree)) tree[letter] = {};
charArr.length && this._addData(tree[letter], charArr);
}
_build() {
this._data.forEach(str => {
this._addData(this.tree, str.split(''));
});
}
_findInTree(tree, keyArr) {
const key = keyArr.shift();
if (!keyArr.length) return true;
if (key in tree) {
return this._findInTree(tree[key], keyArr);
}
return false;
}
has(key) {
return this._findInTree(this.tree, key.split(''));
}
}
const textFile = [
'http://archive.is/',
'http://areyouahuman.com/',
'http://avatars.io/',
'http://beta.mural.ly/',
'http://bli.ms/',
'http://boxjs.com/',
'http://buddypress.org/',
'http://carbonmade.com/',
'http://dochub.io/',
'http://dropr.com/',
'http://epilogger.com/',
'https://google.com',
'http://fontello.com/',
'http://g.etfv.co/'
];
const trie = new Trie(textFile);
console.log('Trie has google.com:', trie.has('https://google.com'));
/* console.log('Trie dump:', JSON.stringify(trie.tree, null, 2)); */