Skip to content

Instantly share code, notes, and snippets.

@thenickreynolds
Created August 17, 2015 02:18
Show Gist options
  • Save thenickreynolds/fb9c1d15fe4f3d61d8e8 to your computer and use it in GitHub Desktop.
Save thenickreynolds/fb9c1d15fe4f3d61d8e8 to your computer and use it in GitHub Desktop.
var TrieNode = function(letter) {
this.letter = letter == null ? null : letter.toUpperCase();
this.children = [];
this.isLeaf = false;
};
TrieNode.prototype.hasChild = function(letter) {
return letter.toUpperCase() in this.children;
};
TrieNode.prototype.contains = function(word) {
if (word.length == 0) {
return this.isLeaf;
}
var letter = word.charAt(0);
if (!this.hasChild(letter)) {
return false;
}
return this.children[letter].contains(word.substring(1));
};
TrieNode.prototype.ensureChild = function(letter) {
letter = letter.toUpperCase();
if (!this.hasChild(letter)) {
this.children[letter] = new TrieNode(letter);
}
}
TrieNode.prototype.getChild = function(letter) {
return this.children[letter.toUpperCase()];
}
function addWordToTrie(root, word) {
var node = root;
for (var i = 0; i < word.length; i++) {
var letter = word.charAt(i);
node.ensureChild(letter);
node = node.getChild(letter);
}
node.isLeaf = true;
}
function createTrie(dictionary) {
var root = new TrieNode(null);
for (var i = 0; i < dictionary.length; i++) {
addWordToTrie(root, dictionary[i]);
}
return root;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment