Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Last active June 12, 2018 20:41
Show Gist options
  • Save pinkmomo027/e07ec0d8932ec84745d4f983967a6aca to your computer and use it in GitHub Desktop.
Save pinkmomo027/e07ec0d8932ec84745d4f983967a6aca to your computer and use it in GitHub Desktop.
Trie Node
class TrieNode {
constructor (value, note="") {
this.value = value;
this.note = note;
this.children = new Array(26);
}
addChildNode (char, value=null) {
let index = char.charCodeAt(0) - 97;
this.children[index] = this.children[index] || new TrieNode(null, char);
if (value) {
this.children[index].value = value;
}
return this.children[index];
}
print (level=0) {
let indent = "";
for (let i = 0; i < level * 2; i++) {
indent += " ";
}
console.log(`${indent}${this.value} (${this.note})`);
this.children.forEach(child => {
if (child) {
child.print(level+1);
}
})
}
insertKey (string, value) {
const length = string.length;
let currentNode = this;
if (length == 0) {
return;
}
for (let i = 0; i < length - 1; i++) {
currentNode = currentNode.addChildNode(string.charAt(i));
}
currentNode.addChildNode(string.charAt(length-1), value);
}
hasKey (string) {
let index = 0, currentNode = this, charCode;
while(index < string.length) {
charCode = string.charCodeAt(index++) - 97;
if (currentNode.children[charCode]) {
currentNode = currentNode.children[charCode];
} else {
return false;
}
}
return !!currentNode.value;
}
getKey (string) {
let index = 0, currentNode = this, char, charCode;
while(index < string.length) {
charCode = string.charCodeAt(index++) - 97;
if (currentNode.children[charCode]) {
currentNode = currentNode.children[charCode];
} else {
return "Not Found";
}
}
return currentNode.value || "Not Found";
}
}
let root = new TrieNode(null, "root");
root.insertKey('xyz', 15);
root.insertKey('xyw', 25);
root.insertKey('xyz', 36);
root.insertKey('xyw', 42);
root.insertKey('xyzp', 15);
root.print();
console.log(root.hasKey('xyz'));
console.log(root.hasKey('xy'));
console.log(root.hasKey(''));
console.log(root.getKey('xyz'));
console.log(root.getKey('xy'));
// null (root)
// null (x)
// null (y)
// 42 (w)
// 36 (z)
// 15 (p)
// true
// false
// false
// 36
// Not Found
// [Finished in 0.1s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment