JSFiddle - React, Tailwind, and code Playground
by LyndseyB
JavaScript
var trie = function () {
this.resultsArray = [],
this.root = {},
this.loadDict();
};
trie.prototype.loadDict = function (dict) {
var dict = ["od", "do", "dog", "dogs", "ods"];
//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++) {
var letter = word[j];
//if theres no branch, create one
if (!(letter in current)) {
current[letter] = {};
}
//set current to the most recent branch
current = current[letter];
}
current.$ = 1;
};
trie.prototype.getWordsNew = function (start, word, result) {
var current = start;
var results = result;
for (var i = 0; i < word.length; i++) { // g o d s
var letter = word[i]; // g
if (letter in current) { // g exists
// store letter g
results += letter;
// set g as the current branch
var cur = current[letter];
//if we've reached the end of a word, store it
if (cur.$ == 1) {
if(this.resultsArray.indexOf(results) < 0) {
newTrie.resultsArray.push(results);
}
}
this.getWordsNew(cur, word.substr(1), results);
results = results.replace(letter, '');
}
}
};
var newTrie = new trie();
var tree = JSON.stringify(newTrie);
//console.log(tree);
newTrie.getWordsNew(newTrie.root, "", "");
console.log(newTrie.resultsArray.join(","));