Skip to content

Instantly share code, notes, and snippets.

@atmin
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atmin/9cd4465046930d4c5ad8 to your computer and use it in GitHub Desktop.
Save atmin/9cd4465046930d4c5ad8 to your computer and use it in GitHub Desktop.
/*
http://codereview.stackexchange.com/questions/25359/simple-trie-implementation-in-javascript
http://jsfiddle.net/4Yttq/9/
*/
function Trie(key) {
this.key = key;
this.value;
}
Trie.prototype.put = function (name, value) {
var node = this,
nameLength = name.length,
i = 0,
currentLetter;
for (i = 0; i < nameLength; i++) {
currentLetter = name[i];
node = node[currentLetter] || (node[currentLetter] = new Trie(currentLetter));
}
node.value = value;
node.name = name;
};
Trie.prototype.get = function (name) {
var node = this,
nameLength = name.length,
i, node;
for (i = 0; i < nameLength; i++) {
if (!(node = node[name[i]])) break;
}
return (i === nameLength) ? node.value : 'not found';
};
// --------
var dict = new Trie();
dict.put("true", "yes");
dict.put("truck", "vehicle");
dict.put("trowel", "dig");
dict.put("hat", "head");
dict.put("halt", "stop");
dict.put("ham", "pig");
dict.put("hammer", "nail");
dict.put("halt", "hold it");
console.log(dict)
console.log("true:", dict.get("true"));
console.log("truck:", dict.get("truck"));
console.log("trowel:", dict.get("trowel"));
console.log("hat:", dict.get("hat"));
console.log("halt:", dict.get("halt"));
console.log("ham:", dict.get("ham"));
console.log("hammer", dict.get("hammer"));
console.log(JSON.stringify(dict));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment