Skip to content

Commit

Permalink
#102 Change Take raises panic if count < 0
Browse files Browse the repository at this point in the history
  • Loading branch information
meian committed Feb 8, 2022
1 parent cac8d94 commit c819bfb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
8 changes: 6 additions & 2 deletions take.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@ type takeIterator[T any] struct {
// itb := gcf.FromSlice([]{1, 2, 3})
// itb = gcf.Take(itb, 2)
//
// If count is 0 or negative, returns empty Iterable.
// If count is 0, returns empty Iterable.
// If count is negative, raises panic.
func Take[T any](itb Iterable[T], count int) Iterable[T] {
if count < 0 {
panic("count for Take must not be negative.")
}
if isEmpty(itb) {
return orEmpty(itb)
}
if count < 1 {
if count == 0 {
return empty[T]()
}
return &takeIterable[T]{itb, count}
Expand Down
23 changes: 19 additions & 4 deletions take_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ func TestTake(t *testing.T) {
count int
}
tests := []struct {
name string
args args
want []int
name string
args args
want []int
wantPanic bool
}{
{
name: "take 1 from slice 3",
Expand Down Expand Up @@ -64,7 +65,7 @@ func TestTake(t *testing.T) {
itb: gcf.FromSlice([]int{1, 2, 3}),
count: -1,
},
want: []int{},
wantPanic: true,
},
{
name: "nil Iterable",
Expand All @@ -74,9 +75,23 @@ func TestTake(t *testing.T) {
},
want: []int{},
},
{
name: "nil and negative",
args: args{
itb: nil,
count: -1,
},
wantPanic: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.wantPanic {
assert.Panics(t, func() {
_ = gcf.Take(tt.args.itb, tt.args.count)
})
return
}
itb := gcf.Take(tt.args.itb, tt.args.count)
s := gcf.ToSlice(itb)
assert.Equal(t, tt.want, s)
Expand Down

0 comments on commit c819bfb

Please sign in to comment.