Skip to content

Commit

Permalink
linkedlist Get接口满足api约束 #2
Browse files Browse the repository at this point in the history
  • Loading branch information
guonaihong committed Jun 11, 2022
1 parent 2e9f61d commit 0db8ef3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
9 changes: 8 additions & 1 deletion linkedlist/linkedlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package linkedlist

import (
"errors"

"github.com/guonaihong/gstl/cmp"
)

Expand Down Expand Up @@ -321,9 +322,15 @@ func (l *LinkedList[T]) ContainsFunc(cb func(value T) bool) bool {
return false
}

// 获取指定索引数据, 忽略错误
func (l *LinkedList[T]) Get(idx int) (e T) {
e, _ = l.GetWithErr(idx)
return
}

// 通过索引查找是否包含这个value
// Get是Index的同义词
func (l *LinkedList[T]) Get(idx int) (e T, err error) {
func (l *LinkedList[T]) GetWithErr(idx int) (e T, err error) {
return l.Index(idx)
}

Expand Down
16 changes: 8 additions & 8 deletions linkedlist/linkedlist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,16 @@ func Test_Last(t *testing.T) {

func Test_Get(t *testing.T) {
// 正索引
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(0)), "1")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(1)), "2")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(2)), "3")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(3)), "4")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(0)), "1")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(1)), "2")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(2)), "3")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(3)), "4")

// 负索引
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(-1)), "4")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(-2)), "3")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(-3)), "2")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").Get(-4)), "1")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(-1)), "4")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(-2)), "3")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(-3)), "2")
assert.Equal(t, must.TakeOne(New[string]().RPush("1", "2", "3", "4").GetWithErr(-4)), "1")
}

func Test_Set(t *testing.T) {
Expand Down

0 comments on commit 0db8ef3

Please sign in to comment.