Skip to content

Instantly share code, notes, and snippets.

@heatherbooker
Created December 10, 2016 17:58
Show Gist options
  • Save heatherbooker/16084c70f50f2ec5f4da967b09c7f8c7 to your computer and use it in GitHub Desktop.
Save heatherbooker/16084c70f50f2ec5f4da967b09c7f8c7 to your computer and use it in GitHub Desktop.
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