Skip to content

Instantly share code, notes, and snippets.

@twfarland
Created March 20, 2015 13:52
Show Gist options
  • Save twfarland/b3364f5b60923c07fcbf to your computer and use it in GitHub Desktop.
Save twfarland/b3364f5b60923c07fcbf to your computer and use it in GitHub Desktop.
Trie
var u = require('util');
var strings = ["1234", "hello", "hell", "1el", "1235"];
var trie = {};
function insert (trie, str) {
var i, ref = trie;
for (i = 0; i < str.length; i++) {
if (!ref[str[i]]) ref[str[i]] = {};
ref = ref[str[i]];
}
ref._ = true;
}
function contains (trie, str) {
var i, ref = trie;
for (i = 0; i < str.length; i++) {
ref = ref[str[i]];
if (!ref) return false;
}
return !!ref._;
}
strings.forEach(function (s) {
insert(trie, s);
});
console.log(u.inspect(trie, { depth: 10 }));
console.log(contains(trie, 'help'));
console.log(contains(trie, 'hell'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment