Skip to content

Instantly share code, notes, and snippets.

@meagtan
Last active September 5, 2016 06:38
Show Gist options
  • Save meagtan/fcd667543cc76e9dc3ed49a557703c96 to your computer and use it in GitHub Desktop.
Save meagtan/fcd667543cc76e9dc3ed49a557703c96 to your computer and use it in GitHub Desktop.
Trie implementation in JavaScript
// Tries are implemented as objects containing values and maps of letters to a value or subtrie.
// Construct trie from given list of strings (optional, defaults to 0)
function Trie(strings) {
this.value = null;
this.nodes = {};
if (strings !== undefined)
for (var str in strings)
this.addString(str);
};
// Add str to trie
Trie.prototype.addString = function(str, value) {
var root = this;
value = value || true; // default value is true
for (var i in str) {
if (!root.nodes.hasOwnProperty(str[i]))
root.nodes[str[i]] = Trie(); // create new node corresponding to str[i]
root = root.nodes[str[i]]; // traverse down
}
// set value of node
root.value = value;
};
// Get value of str, or null if str not in trie
Trie.prototype.valueOf = function(str) {
var root = this;
// traverse down trie
for (var i in str) {
if (!root.nodes.hasOwnProperty(str[i])) // can't traverse further
return false;
root = root.nodes[str[i]]; // traverse down
}
return root.value;
};
// Return matcher that, when applied to a string, replaces instances of a word s in trie with fun(s)
Trie.prototype.matcher = function(fun) {
fun = fun || (str => this.valueOf(str))
return str => {
var len = str.length;
var res = "";
var found = false;
for (var i = 0, j = 0; i < len; i++) {
// traverse trie until a match or a dead end
j = i;
found = false;
for (var root = this; j < len && root.nodes.hasOwnProperty(str[j]) && !found; j++, root = root.nodes[str[j]]) {
if (root.value) { // found match
res += fun(str.substring(i, j + 1));
i = j; // move after match
found = true;
}
}
if (!found)
res += str.charAt(i);
}
return res;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment