Created
October 29, 2018 03:56
-
-
Save lukearno/334e5799de1a2129ec46b90669a62706 to your computer and use it in GitHub Desktop.
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
package main | |
import "fmt" | |
type Trie struct { | |
Children map[rune]*Trie | |
End bool | |
} | |
func NewTrie() *Trie { | |
return &Trie{End: false, Children: map[rune]*Trie{}} | |
} | |
func (n *Trie) Insert(cmd *string) { | |
for _, r := range *cmd { | |
nn, ok := n.Children[r] | |
if ok == false { | |
nn = NewTrie() | |
n.Children[r] = nn | |
} | |
n = nn | |
} | |
n.End = true | |
} | |
func (n *Trie) Find(cmd *string) *Trie { | |
var ok bool | |
for _, r := range *cmd { | |
n, ok = n.Children[r] | |
if ok == false { | |
return nil | |
} | |
} | |
return n | |
} | |
func (n *Trie) Complete(base *string) []string { | |
var comp string | |
var comps []string | |
for k, v := range n.Children { | |
comp = *base + string(k) | |
if v.End == true { | |
comps = append(comps, comp) | |
} | |
if len(v.Children) != 0 { | |
comps = append(comps, v.Complete(&comp)...) | |
} | |
} | |
return comps | |
} | |
func (n *Trie) Completions(cmd *string) []string { | |
n = n.Find(cmd) | |
if n == nil { | |
return nil | |
} | |
return n.Complete(cmd) | |
} | |
func Completer(cmds []string) (trie *Trie) { | |
trie = NewTrie() | |
for _, cmd := range cmds { | |
trie.Insert(&cmd) | |
} | |
return | |
} | |
var COMMANDS = []string{ | |
"python", | |
"python -i", | |
"python -c", | |
"git", | |
"git help", | |
"grep", | |
"go run", | |
"go build"} | |
var INPUTS = []string{ | |
"g", | |
"gi", | |
"git h", | |
"p", | |
"python", | |
"x"} | |
func main() { | |
t := Completer(COMMANDS[:]) | |
for _, i := range INPUTS { | |
fmt.Println(i + ": ----------") | |
comps := t.Completions(&i) | |
if comps != nil { | |
for _, c := range comps { | |
fmt.Println(" ", c) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment