Skip to content

Instantly share code, notes, and snippets.

@tingwei628
Created August 7, 2016 04:24
Show Gist options
  • Save tingwei628/94ff5b090955c266f6bab9d3e4d186ae to your computer and use it in GitHub Desktop.
Save tingwei628/94ff5b090955c266f6bab9d3e4d186ae to your computer and use it in GitHub Desktop.
Demo how to write Trie
function TrieNode() {
this.key = null;
this.children = {};
this.isNode = false;
}
function insert(word, r) {
var start = r;
for(var index = 0, le = word.length; index<le; index++) {
if (!start.children.hasOwnProperty(word[index])) {
var t = new TrieNode();
t.key = word[index];
if (index === le - 1) {
t.isNode = true;
}
start.children[word[index]] = t;
} else {
if(index === le - 1) {
start.isNode = true;
}
}
start = start.children[word[index]];
}
return r;
}
function search(word, r) {
var start = r;
var isFound;
if (Object.keys(r).length === 0) {
return false;
}
for(var j=0, le=word.length; j<le; j++) {
if(start.children.hasOwnProperty(word[j])) {
start = start.children[word[j]];
if (j === le - 1 && start.isNode) {
isFound = true;
} else {
isFound = false;
}
} else {
isFound = false;
break;
}
}
return isFound;
}
var sources = ["the", "a", "there", "answer", "any","by", "bye", "their"]; // sources
var root = new TrieNode();
for (var i=0, len = sources.length; i<len; i++) {
root = insert(sources[i], root); // insert each word
}
search('by', root); // search whether this word exist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment