Skip to content

Commit

Permalink
feat: add Displayable and SelecteDisplayable to show more information
Browse files Browse the repository at this point in the history
  • Loading branch information
metacosm committed Mar 23, 2020
1 parent 046ad06 commit e205663
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
62 changes: 62 additions & 0 deletions pkg/ui/displayable.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ui

import (
"sort"
"strings"
)

type Displayable interface {
Help() string
Display() string
Name() string
GetUnderlying() interface{}
}

type DisplayableMap struct {
byNames map[string]Displayable
byIndex []Displayable
}

var Empty = DisplayableMap{}

func NewDisplayableMap(size int) DisplayableMap {
return DisplayableMap{
byNames: make(map[string]Displayable, size),
byIndex: make([]Displayable, 0, size),
}
}

func (d *DisplayableMap) Add(displayable Displayable) {
d.byNames[displayable.Name()] = displayable
d.byIndex = append(d.byIndex, displayable)
}

func (d DisplayableMap) Len() int {
return len(d.byIndex)
}

func (d DisplayableMap) Less(i, j int) bool {
return strings.Compare(d.byIndex[i].Display(), d.byIndex[j].Display()) == -1
}

func (d DisplayableMap) Swap(i, j int) {
d.byIndex[j] = d.byIndex[i]
}

func (d DisplayableMap) AsDisplayableOptions() []string {
result := make([]string, 0, d.Len())
for _, displayable := range d.byIndex {
result = append(result, displayable.Display())
}
sort.Strings(result)
return result
}

func (d DisplayableMap) GetByIndex(i int) Displayable {
return d.byIndex[i]
}

func (d DisplayableMap) GetByName(name string) (Displayable, bool) {
displayable, ok := d.byNames[name]
return displayable, ok
}
8 changes: 6 additions & 2 deletions pkg/ui/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@ func Select(message string, options []string, defaultValue ...string) string {
return doSelect(message, options, defaultValue)
}

func SelectUnsorted(message string, options []string, defaultValue ...string) string {
return doSelect(message, options, defaultValue)
func SelectDisplayable(message string, options DisplayableMap, defaultValue ...string) Displayable {
sort.Sort(options)
displayableOptions := options.AsDisplayableOptions()
name := doSelect(message, displayableOptions, defaultValue)
displayable, _ := options.GetByName(name)
return displayable
}

func doSelect(message string, options []string, defaultValue []string) string {
Expand Down

0 comments on commit e205663

Please sign in to comment.