Created
December 10, 2016 17:58
-
-
Save heatherbooker/16084c70f50f2ec5f4da967b09c7f8c7 to your computer and use it in GitHub Desktop.
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
const words = ['dark', 'dapper']; | |
let trie = []; | |
words.forEach(word => { | |
addToTrie(word, 0, trie); | |
}); | |
function addToTrie(word, letterIndex, arrToAddNodeTo) { | |
let isEnd = false; | |
if (letterIndex == word.length - 1) { | |
isEnd = true; | |
} | |
let newNode; | |
for (let i = letterIndex; i < arrToAddNodeTo.length; i++) { | |
console.log(arrToAddNodeTo[i].value, word[letterIndex]); | |
if (arrToAddNodeTo[i].value == word[letterIndex]) { | |
addToTrie(word, ++letterIndex, arrToAddNodeTo); | |
} else { | |
break; | |
} | |
} | |
if (isEnd) { | |
console.log('the end', trie); | |
return; | |
} | |
newNode = {value: word[letterIndex], isEnd, rest: []}; | |
arrToAddNodeTo.push(newNode); | |
addToTrie(word, ++letterIndex, newNode.rest); | |
} | |
console.log(JSON.stringify(trie, null, 2)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment