Please help me find the error in following code. when i tried to debug it logs ‘this is undefined’ five times.
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var Node = function() {
this.keys = new Map();
this.end = false;
this.setEnd = function() {
this.end = true;
};
this.isEnd = function() {
return this.end;
};
};
var Trie = function() {
// change code below this line
this.root = new Node();
this.add = function(word){
if(!this.isWord(word) && word != null){
let chars = word.split('');
let currNode = this.root;
for(let char in chars){
if(!currNode.keys.has(char)){
currNode.keys.set(char, new Node());
}
currNode = currNode.keys.get(char);
}
currNode.setEnd();
}
}
this.print = function(){
let words = new Array();
let word = '';
let wordMaker = function(node){
if(node.isEnd){
words.push(word);
}
if(node.keys.size > 0){
for(let key in node.keys.keys()){
word.concat(key);
wordMaker(node.keys.get(key));
}
}
word = word.slice(0, -1);
}
wordMaker(this.root);
return words;
}
this.isWord = function(word){
if(word != null){
let chars = word.split('');
let currNode = this.root;
for(let char in chars){
if(currNode.keys.has(char)){
currNode = currNode.keys.get(char);
}
else{
return false;
}
}
return currNode.isEnd == true;
}
return false;
}
// change code above this line
};
let tree = Trie();
tree.add('one');
tree.add('oneness')
tree.add('oneder');
tree.print();
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-trie-search-tree/