Skip to content

Commit

Permalink
Added generic list example
Browse files Browse the repository at this point in the history
  • Loading branch information
mmontes11 committed Feb 28, 2022
1 parent 38f9803 commit 42cff7e
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
58 changes: 58 additions & 0 deletions list/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package list

import (
"errors"
"fmt"
)

type List[T any] struct {
arr []T
}

func (l *List[T]) Add(item ...T) {
l.arr = append(l.arr, item...)
}

type FindFn[T any] func(index int, item T) bool

func (l *List[T]) FindWhere(fn FindFn[T]) (int, error) {
for i, v := range l.arr {
if fn(i, v) {
return i, nil
}
}
return -1, nil
}

func (l *List[T]) Remove(index int) error {
if err := l.checkIndex(index); err != nil {
return err
}
l.arr = append(l.arr[:index], l.arr[index+1:]...)
return nil
}

func (l *List[T]) Update(index int, value T) error {
if err := l.checkIndex(index); err != nil {
return err
}
l.arr[index] = value
return nil
}

func (l *List[T]) checkIndex(index int) error {
if index < 0 || index > (len(l.arr)-1) {
return errors.New("index out of bounds")
}
return nil
}

func (l *List[T]) String() string {
return fmt.Sprintf("%v len=%d cap=%d", l.arr, len(l.arr), cap(l.arr))
}

func NewList[T any]() *List[T] {
return &List[T]{
arr: []T{},
}
}
38 changes: 38 additions & 0 deletions list/list_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package list_test

import (
"fmt"
"github.com/coruna-gophers/generics-poc/list"
"testing"
)

func TestList(t *testing.T) {
l := list.NewList[int]()
fmt.Println(l)

l.Add(1, 2, 3)
fmt.Println(l)

l.Remove(0)
fmt.Println(l)

l.Add(4)
fmt.Println(l)

l.Add(5, 6)
fmt.Println(l)

l.Update(3, 10)
fmt.Println(l)

var findFn list.FindFn[int]
findFn = func(index int, item int) bool {
return item%2 == 0
}

index, err := l.FindWhere(findFn)
if err != nil {
t.Fatalf("error finding first even element: %v", err)
}
fmt.Printf("first event element at %d\n", index)
}

0 comments on commit 42cff7e

Please sign in to comment.