-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrieSymbolTable.js
77 lines (56 loc) · 1.06 KB
/
TrieSymbolTable.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
class Node {
#value
#next
constructor () {
this.#value = null
this.#next = []
}
get value() {
return this.#value
}
get next() {
return this.#next
}
set value(value) {
this.#value = value
}
}
class TrieSymbolTable {
#root
constructor () {
this.#root = null
}
#getNodeValue (node, key, d) {
if (!node) {
return null
}
if (d === key.length) {
return node
}
const letter = key.charAt(d)
return this.#getNodeValue(node.next[letter], key, d + 1)
}
get (key) {
const node = this.#getNodeValue(this.#root, key, 0)
if (!node) {
return null
}
return node.value
}
#putNode (node, key, value, d) {
if (!node) {
node = new Node()
}
if (d === key.length) {
node.value = value
return node
}
const letter = key.charAt(d)
node.next[letter] = this.#putNode(node.next[letter], key, value, d + 1)
return node
}
put (key, value) {
this.#root = this.#putNode(this.#root, key, value, 0)
}
}
module.exports = TrieSymbolTable