Trie Construction from the data

by rishul matta

JavaScript

/**
 * @param {string[]} dictionary
 * @param {string} sentence
 * @return {string}
 */
var replaceWords = function(dictionary, sentence) {
    // var dictionary = ["cat","bat","rat"] 
    
    class Node {
        constructor(value, isRoot, childNode) {
            this.value = value;
            this.isRoot = isRoot;
            this.children = {};
            if (childNode) {
                this.children = {[childNode.value]: childNode};
            }
            
        }
        
    
    }
    
    class Trie {
        constructor() {
            this.root = {children: {}};
        }
        
        _recursivelyGetRootPrefix(word, parent, rootPrefix) {
            const ch = word.substring(0, 1);
            const node = parent.children[ch];
            
            if (node) {
                rootPrefix += ch;
                if (node.isRoot) {
                    return rootPrefix;
                }
                
                return this._recursivelyGetRootPrefix(word.substring(1), node, rootPrefix);
            }
            
            return '';
            
        }
        
        getRootPrefix(word) {
            return this._recursivelyGetRootPrefix(word, this.root, '');
        }
        
        _recurSivelyAddWord(word, node) {

            if (!word) {
                return;
            }
            
            const ch = word.substring(0, 1);
					 const existingNode = node.children[ch];
            
            if (existingNode) {
                if (ch === word) {
                    existingNode.isRoot = true;
                } else {
                    this._recurSivelyAddWord(word.substring(1), existingNode);
                }
            } else {
                const newNode = new Node(ch, ch == word, null);
                node.children[newNode.value] =  newNode;
                this._recurSivelyAddWord(word.substring(1), newNode);
            }
            
        }
        
        addWord(word) {
           ...