Skip to content

Commit 5914947

Browse files
committed
update: TrieNode, insert() in Trie
1 parent 72f5ba5 commit 5914947

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class TrieNode {
2+
constructor(char) {
3+
this.char = char;
4+
this.children = [];
5+
this.isEndOfWord = false;
6+
7+
// mark all the alphabets as null
8+
for (let i = 0; i < 26; i += 1) this.children[i] = null;
9+
}
10+
11+
markAsLeaf() {
12+
this.isEndOfWord = true;
13+
}
14+
15+
unmarkAsLeaf() {
16+
this.isEndOfWord = false;
17+
}
18+
}
19+
20+
module.exports = TrieNode;
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const Node = require('./Node');
2+
3+
class Trie {
4+
constructor() {
5+
this.root = new Node('');
6+
}
7+
8+
insert(key) {
9+
if (!key) {
10+
return false;
11+
}
12+
13+
// convert to lower case
14+
// keys are basically words
15+
const word = key.toLowerCase();
16+
let currentNode = this.root;
17+
18+
for (let level = 0; level < word.length; level += 1) {
19+
const index = this.getIndexOfChar(word[level]);
20+
if (!currentNode.children[index]) {
21+
currentNode.children[index] = new Node(word[level]);
22+
}
23+
currentNode = currentNode.children[index];
24+
}
25+
26+
// when we are done with inserting all the character of the word,
27+
// mark the node as end leaf
28+
currentNode.markAsLeaf();
29+
return true;
30+
}
31+
32+
// helper to get the index of a character
33+
// eslint-disable-next-line class-methods-use-this
34+
getIndexOfChar(char) {
35+
return char.charCodeAt(0) - 'a'.charCodeAt(0);
36+
}
37+
}
38+
39+
module.exports = Trie;

0 commit comments

Comments
 (0)