Skip to content

Instantly share code, notes, and snippets.

@mdibaiee
Created July 24, 2015 03:50
Show Gist options
  • Save mdibaiee/7d516b2e1cc460eabac2 to your computer and use it in GitHub Desktop.
Save mdibaiee/7d516b2e1cc460eabac2 to your computer and use it in GitHub Desktop.
Trie
export default class Trie {
constructor(value = '') {
this.value = value;
this.children = [];
}
add(value) {
let parent = this;
for (let i = 0, len = value.length; i < len; i++) {
let key = value.slice(0, i + 1);
let node = parent.find(key);
if (!node) {
node = new Trie(key);
parent.children.push(node);
}
parent = node;
}
return parent;
}
find(search) {
let node = this;
let key = '';
for (let char of search) {
key += char;
node = this.children.find(child => child.value === key);
if (!node) return null;
}
return node;
}
}
@lienista
Copy link

lienista commented Feb 7, 2020

The operation .find is O(n) to search. it's better to set this.children={} to achieve O(1) look up

@mdibaiee
Copy link
Author

mdibaiee commented Feb 9, 2020

@lienista you are right, there was no real effort to optimize this, but rather the focus was to explain the underlying idea as simple as possible, but perhaps a map would be easier than an array for explanation, too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment