Skip to content

Instantly share code, notes, and snippets.

@danallison
Created November 17, 2013 20:05
Show Gist options
  • Save danallison/7517638 to your computer and use it in GitHub Desktop.
Save danallison/7517638 to your computer and use it in GitHub Desktop.
Trie data structure in CoffeeScript
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