Created
July 24, 2015 03:50
-
-
Save mdibaiee/7d516b2e1cc460eabac2 to your computer and use it in GitHub Desktop.
Trie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
The operation
.find
is O(n) to search. it's better to setthis.children={}
to achieve O(1) look up