class AutoCompleter
constructor: ->
@trie = {}
add: (word) ->
root = @trie
for c in word
if !root[c]?
root[c] = {}
root = root[c]
suggest: (prefix) ->
root = @trie
word = ""
words = []
for c in prefix
return word unless root[c]?
root = root[c]
word = word + c
@getWords(root, word, words)
words
getWords: (root, word, words) ->
if _.isEmpty(root)
words.push word
else
for key, value of root
@getWords(value, word + key, words)
autoComplete: ->
words = @suggest $('#search').val()
html = """
<p>Results: </p>
<ul>
"""
for w in words
html += "<li>#{w}</li>"
html += '</ul>'
$('#result').html html
ac = new AutoCompleter
ac.add 'amy'
ac.add 'ann'
$('button').click -> ac.add $('#word').val()
$('#search').on 'input', -> ac.autoComplete()
<p>Add to Trie:
<input type="textbox" id='word'></input>
<button type='button' name='add'>add word</button>
</p>
<p>Search:
<input type='textbox' id='search' />
</p>
<p>
<div id='result'></div>
</p>
External resources loaded into this fiddle: