Skip to content

Instantly share code, notes, and snippets.

@tlivings
Created October 9, 2014 02:02
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 tlivings/1e92fe37c8544c6ce2b1 to your computer and use it in GitHub Desktop.
Save tlivings/1e92fe37c8544c6ce2b1 to your computer and use it in GitHub Desktop.
trie
'use strict';
function Trie() {
this.children = {};
}
Trie.prototype = {
search: function (str) {
var current = this;
for (var idx = 0; idx < str.length; idx++) {
current = current.children[str[idx]];
if (!current) {
return undefined;
}
}
return current.end ? current : undefined;
},
insert: function (str) {
var current = this;
for (var idx = 0; idx < str.length; idx++) {
current = current.children[str[idx]] || (current.children[str[idx]] = new Node(str[idx], (idx + 1) >= str.length));
}
current.end = true;
}
};
function Node(value, end) {
Node.super_.apply(this);
this.value = value;
this.end = end;
}
require('util').inherits(Node, Trie);
module.exports = Trie;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment