Created
October 9, 2014 02:02
-
-
Save tlivings/1e92fe37c8544c6ce2b1 to your computer and use it in GitHub Desktop.
trie
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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