Skip to content

Instantly share code, notes, and snippets.

@nhnam
Created January 1, 2022 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhnam/f9de96a742babd06407da386e2abe11e to your computer and use it in GitHub Desktop.
Save nhnam/f9de96a742babd06407da386e2abe11e to your computer and use it in GitHub Desktop.
class TrieNode {
constructor(key) {
this.key = key;
this.parent = null;
this.children = {};
this.end = false;
}
};
class Trie {
constructor() {
this.root = new TrieNode(null);
}
}
TrieNode.prototype.getWord = function() {
let output = [];
let node = this;
while (node !== null) {
output.splice(0, 0, node.key);
node = node.parent;
}
return output.join('');
}
Trie.prototype.insert = function(word) {
let node = this.root;
for(let i = 0; i < word.length; i++) {
let c = word[i];
if(!node.children[c]) {
// not exits -> init new trieNode for c
node.children[c] = new TrieNode(c);
node.children[c].parent = node;
}
// go inside trieNode c
node = node.children[c];
// guard check if we reached end of the word
if(i === word.length - 1) {
node.end = true;
}
}
}
Trie.prototype.contains = function(word) {
let node = this.root;
for(let i = 0; i < word.length; i++) {
let c = word[i];
if(!node.children[c]) {
return false;
} else {
node = node.children[c];
}
}
return node.end;
}
Trie.prototype.find = function(prefix) {
var node = this.root;
var output = [];
// find the last node of prefix
for(let i = 0; i < prefix.length; i++) {
let c = prefix[i];
if(node.children[c]) {
node = node.children[c];
} else {
return output;
}
}
findAllWords(node, output);
return output;
}
function findAllWords(node, arr) {
if(node.end) {
arr.splice(0,0, node.getWord())
}
// collect all words
for (let c in node.children) {
findAllWords(node.children[c], arr);
}
}
let trie = new Trie();
trie.insert('Hello');
trie.insert('World');
trie.insert('Hellium');
trie.insert('Hellboyy');
trie.insert('Hello World!');
// check if trie contains whole word
console.log(trie.contains('Hello World!')); // true
console.log(trie.find('Hel')); // ["Hellboyy", "Hellium", "Hello World!", "Hello"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment