Created
November 17, 2013 20:05
-
-
Save danallison/7517638 to your computer and use it in GitHub Desktop.
Trie data structure in CoffeeScript
This file contains 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
class Trie | |
constructor: (strings = [], @root = {}) -> | |
@addString string for string in strings | |
addString: (string) -> | |
chars = string.split "" | |
string = "" | |
node = @root | |
for char in chars | |
string += char | |
node[string] ||= { _complete: false } | |
node = node[string] | |
node._complete = true | |
containsString: (string) -> | |
chars = string.split "" | |
string = "" | |
node = @root | |
for char in chars | |
string += char | |
return false unless (node = node[string])? | |
return true | |
stringsWithPrefix: (prefix) -> | |
chars = prefix.split "" | |
string = "" | |
node = @root | |
completeStrings = [] | |
for char in chars | |
string += char | |
return null unless (node = node[string])? | |
remainingNodes = [node] | |
while remainingNodes.length | |
currentNode = remainingNodes.shift() | |
for key, subNode of currentNode | |
remainingNodes.push subNode | |
completeStrings.push key if subNode._complete | |
return completeStrings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment