Skip to content

Commit

Permalink
Fix list index when item doesn't support comparison (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
҈҈҈Luiz Branco authored Nov 16, 2017
1 parent 6b68b09 commit ab0f0c6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
13 changes: 7 additions & 6 deletions list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ const NotFound = -1
// visible items. The list can be moved up, down by one item of time or an
// entire page (ie: visible size). It keeps track of the current selected item.
type List struct {
items []interface{}
scope []interface{}
items []*interface{}
scope []*interface{}
cursor int // cursor holds the index of the current selected item
size int // size is the number of visible options
start int
Expand All @@ -37,10 +37,11 @@ func New(items interface{}, size int) (*List, error) {
}

slice := reflect.ValueOf(items)
values := make([]interface{}, slice.Len())
values := make([]*interface{}, slice.Len())

for i := range values {
values[i] = slice.Index(i).Interface()
item := slice.Index(i).Interface()
values[i] = &item
}

return &List{size: size, items: values, scope: values}, nil
Expand Down Expand Up @@ -77,7 +78,7 @@ func (l *List) CancelSearch() {
}

func (l *List) search(term string) {
var scope []interface{}
var scope []*interface{}

for i, item := range l.items {
if l.Searcher(term, i) {
Expand Down Expand Up @@ -189,7 +190,7 @@ func (l *List) Items() ([]interface{}, int) {
active = j
}

result = append(result, l.scope[i])
result = append(result, *l.scope[i])
}

return result, active
Expand Down
46 changes: 46 additions & 0 deletions list/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,52 @@ func TestListPageDown(t *testing.T) {
})
}

func TestListComparion(t *testing.T) {
t.Run("when item supports comparison", func(t *testing.T) {
type comparable struct {
Number int
}

structs := []comparable{
{Number: 1},
{Number: 2},
}

l, err := New(structs, 4)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}

idx := l.Index()

if idx != 0 {
t.Errorf("expected index to be first, got %d", idx)
}
})

t.Run("when item doesn't support comparison", func(t *testing.T) {
type uncomparable struct {
Numbers []int
}

structs := []uncomparable{
{Numbers: []int{1}},
{Numbers: []int{2}},
}

l, err := New(structs, 4)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}

idx := l.Index()

if idx != 0 {
t.Errorf("expected index to be first, got %d", idx)
}
})
}

func castList(list []interface{}) []rune {
result := make([]rune, len(list))
for i, l := range list {
Expand Down

0 comments on commit ab0f0c6

Please sign in to comment.