-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.js
55 lines (49 loc) · 1.26 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
'use strict'
function Trie() {
this.head = {
children: {}
}
}
Trie.prototype.add = function (key) {
let curIndex = 0,
curNode = this.head
while(typeof curNode.children[key[curIndex]] !== 'undefined' && curIndex < key.length) {
curNode = curNode.children[key[curIndex]]
curIndex += 1
}
while(curIndex < key.length) {
curNode.children[key[curIndex]] = {
wordEnd: curIndex === key.length - 1,
children: {}
}
curNode = curNode.children[key[curIndex]]
curIndex += 1
}
}
Trie.prototype.search = function (key) {
let curIndex = 0,
curNode = this.head
while(typeof curNode.children[key[curIndex]] !== 'undefined' && curIndex < key.length) {
curNode = curNode.children[key[curIndex]]
if(curIndex === key.length - 1 && curNode.wordEnd) {
return { status: true, hasWordChain: hasProperties(curNode.children) }
}
curIndex += 1
}
let hasWordChain
if(curIndex < key.length - 1) {
hasWordChain = typeof curNode.children[key[curIndex]] !== 'undefined'
}
else {
hasWordChain = hasProperties(curNode.children)
}
return { status: false, hasWordChain }
}
function hasProperties(o) {
for(let prop in o) {
if(o.hasOwnProperty(prop))
return true
}
return false
}
module.exports = Trie