Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created October 31, 2021 07:15
Show Gist options
  • Select an option

  • Save ahamed/4e569d00ade1ff19408bc8adbd489d6c to your computer and use it in GitHub Desktop.

Select an option

Save ahamed/4e569d00ade1ff19408bc8adbd489d6c to your computer and use it in GitHub Desktop.
Implement the Trie data structure for storing worlds in an efficient way.
function Node(character) {
this.value = character;
this.endOfWord = false;
this.children = {};
}
class Trie {
constructor() {
this.root = new Node(null);
}
insert(word) {
let current = this.root;
for (let char of word) {
if (current.children[char] === undefined) {
current.children[char] = new Node(char);
}
current = current.children[char];
}
current.endOfWord = true;
}
search(word) {
let current = this.root;
for (let char of word) {
if (current.children[char] === undefined) {
return false;
}
current = current.children[char];
}
return current.endOfWord;
}
}
const trie = new Trie();
trie.insert('hello');
trie.insert('world');
console.log(trie.search('world'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment