Skip to content

Instantly share code, notes, and snippets.

@kulicuu
Last active July 28, 2017 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kulicuu/c594ecb9f77c6989e39ef852b0ec98db to your computer and use it in GitHub Desktop.
Save kulicuu/c594ecb9f77c6989e39ef852b0ec98db to your computer and use it in GitHub Desktop.
autocorrect with efficient tree data structure
global.c = console.log.bind console
global._ = require 'lodash'
global.fs = require 'fs'
global.color = require 'bash-color'
c 'hi'
require './globals.coffee'
lookup_node_at_prefix = ({ prefix, tree }) ->
cursor = tree
prefix_rayy = prefix.split ''
for char in prefix_rayy
cursor = cursor.chd_nodes[char]
# c cursor is undefined
if cursor is undefined
return 'Not found.'
return cursor
break_ties = ({ candides }) ->
# for now will just return the first,
# but later can implement the logic for lexicographic order
candides[0]
map_prefix_to_word = ({ dictionary, prefix }) ->
# c color.green prefix
# c dictionary
candides = []
for word in dictionary
if word.indexOf(prefix) is 0
candides.push word
if candides.length > 1
return break_ties { candides }
else
return candides.pop()
blob = fs.readFileSync 'string_dictionary.txt', 'utf8'
the_dictionary = blob.split '\n'
the_dictionary = _.map the_dictionary, (word, idx) ->
word.toLowerCase()
c the_dictionary
tree =
chd_nodes: {}
prefix: ''
for word, idx in the_dictionary
cursor = tree
prefix = ''
unless word.length < 1
for char, jdx in word
prefix+= char
if not _.includes(_.keys(cursor.chd_nodes), char)
cursor.chd_nodes[char] =
match_word: map_prefix_to_word({ prefix, dictionary: the_dictionary })
prefix: prefix
chd_nodes: {}
cursor = cursor.chd_nodes[char]
c tree
c color.green "\n \n So now everything is built. \n \n"
# test:
prefix_000 = 'cece'
the_node = lookup_node_at_prefix
prefix: prefix_000
tree: tree
c the_node
{
"dependencies": {
"bash-color": "latest",
"commander": "latest",
"lodash": "latest"
}
}
aardvark
armadillo
armament
bevy
between
betwixt
cavalier
canteen
lamarkian
landmark
llama
suave
submarine
tipsy
trenton
zebra
@kulicuu
Copy link
Author

kulicuu commented Jul 27, 2017

I'm using nodemon so to test I just edit prefix_000's value on line 64 and click save. The terminal should be side-by-side with the text-editor so you can test pretty much live like that.

Assumes:

  • nodemon and coffee installed globally, npm i ran locally for the package.json contents.
  • The above files are in a common dir and nodemon main_000.coffee.

@kulicuu
Copy link
Author

kulicuu commented Jul 28, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment