Here is the 'constructor' function as well as the 'inset' method I created...
function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
let node = new Trie(null);
for(let character of string) {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
}
node = node.children[character];
}
node.endOfWord = true;
};
Here is the test case I created...
let trie = new Trie;
trie.insert('hello');
console.log(trie)
the output for the console log is...
Trie { value: undefined, endOfWord: false, children: {} }
based on my input into the 'insert' function I was expecting...
Trie { value: 'h', endOfWord: false, children: {value: 'e', endOfWord: false, children: {value: 'l', endOfWord: false, children: {value: 'l', endOfWord: false, children: {value: 'o', endOfWord: false, children: {}}}}} }
Any clues or tips as to why this isn't adding the children correctly?
Thanks for your time!
You need to use the children on the instance you are on, not the new instance you created.
So when you do let node = new Trie(null); you are creating a new instance. You are adding the children to that, not the current instance you already created.
function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
let node = this;
for(let character of string) {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
}
node = node.children[character];
}
node.endOfWord = true;
};
let trie = new Trie;
trie.insert('hello');
console.log(trie)
You are just creating a new Trie node and assign all property to it. You are not using it anywhere.
You are considering node inside the insert function as the object which is calling it and you should assign all the property as a children:
let node = this;
You can directly use this but for simplicity I've just assign the current object to the node
function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
const node = this;
string.split("").forEach((character, index) => {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
if (index === string.length - 1)
node.children[character].endOfWord = true;
}
});
};
let trie = new Trie();
trie.insert("hello");
console.log(trie);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }