Skip to content

Commit

Permalink
feat: Add error message with index and length information
Browse files Browse the repository at this point in the history
This commit updates the code in `genericlist.go` to improve error handling in the `Remove` method. A more descriptive error message is now generated when the index is out of range. The new error message includes both the index and the length of the list. This change improves the user experience by providing more helpful information when an error occurs.
  • Loading branch information
jvanrhyn committed Oct 14, 2023
1 parent 456294d commit 2bee94a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cmd/genericlist/genericlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// the standard comparison operators (<, >, ==, etc.).
package genericlist

import "fmt"

// GenericList represents a type-safe, dynamic list of comparable items.
type GenericList[T comparable] struct {
data []T
Expand All @@ -22,7 +24,8 @@ func (g *GenericList[T]) Add(value T) {
// Panics if the index is out of bounds.
func (g *GenericList[T]) Remove(i int) {
if i < 0 || i > len(g.data)-1 {
panic("index is out of range")
msg := fmt.Sprintf("index is out of range: %d : %d", i, len(g.data))
panic(msg)
}
g.data = append(g.data[:i], g.data[i+1:]...)
}
Expand Down
42 changes: 42 additions & 0 deletions cmd/genericlist/genericlist_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package genericlist

import (
"math/rand"
"testing"
)

Expand Down Expand Up @@ -562,3 +563,44 @@ func shouldPanic(t *testing.T, f func()) {
f()
t.Errorf("should have panicked")
}

func BenchmarkAdd(b *testing.B) {
list := &GenericList[int]{}
list.New()

for i := 0; i < b.N; i++ {
list.Add(rand.Intn(100))
}
}

func BenchmarkRemove(b *testing.B) {
list := &GenericList[int]{}
list.New()

for i := 0; i < 1000; i++ {
list.Add(rand.Int())
}

b.ResetTimer()

for i := 0; i < b.N; i++ {
list.RemoveByValue(rand.Int())
}
}

func BenchmarkMap(b *testing.B) {
list := &GenericList[int]{}
list.New()

for i := 0; i < 1000; i++ {
list.Add(rand.Intn(100))
}

b.ResetTimer()

for i := 0; i < b.N; i++ {
list.Map(func(item int) int {
return item * 2
})
}
}

0 comments on commit 2bee94a

Please sign in to comment.