JSFiddle - React, Tailwind, and code Playground

by LyndseyB

HTML

var trie = function () {
    this.resultsArray = [],
    this.root = {},
    this.loadDict(dictionary);
};

trie.prototype.loadDict = function (dict) {
    //var dict = ["dog", "dogs", "god", "gods", "cat", "sod", "od", "dos", "do"];
    
    //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) {
                //console.log(results);
                newTrie.resultsArray.push(results);
            }
            // go deeper, whilst removing the current letter, so it becomes o d s            
            this.getWordsNew(cur, word.replace(letter, ''), results);
        }
        results = results.replace(letter, '');
    }
};

var newTrie = new trie();
//var tree = JSON.stringify(newTrie);

//newTrie.getWordsNew(newTrie.root, "staler", "");

//console.log(newTrie.resultsArray.join(","));