Simple Trie Structure
by LyndseyB
JavaScript
var dictionary = ["she", "sh", "he", "hes", "eh"];
var trie = function() {
this.root = {};
};
trie.prototype.loadDict = function(dict) {
//loop through dictionary to create trie
for(var i=0; i<dict.length; i++) {
var word = dict[i];
this.addNode(word);
}
};
trie.prototype.addNode = function(word) {
//current branch
var current = this.root;
//loop through letters to create branches
for(var j=0; j<word.length; j++) {
//if theres no branch, create one
if(!(word[j] in current)) {
current[word[j]] = {};
}
//set current to the most recent branch
current = current[word[j]]
}
current.$=1;
}
trie.prototype.findWords = function(start, word) {
var current = start; //first : root {}
var firstChar = word.charAt(0); //first character : s
//first char exists in tree
if( firstChar in current ) {
//set this as the current branch
current = current[firstChar];
if (current.$==1) {
console.log("word found");
}
myTrie.findWords(current, word.substr(1));
}
}
var myTrie = new trie();
myTrie.loadDict(dictionary);
myTrie.findWords(myTrie.root, "she");
//console.log(JSON.stringify(myTrie));