From fcc404a0c72fb3a43b12539ac61a059aec53ba16 Mon Sep 17 00:00:00 2001 From: kitamin <11195207+meian@users.noreply.github.com> Date: Wed, 9 Feb 2022 00:46:36 +0900 Subject: [PATCH] #102 Change TakeLast raises panic if count < 0 --- take_last.go | 8 ++++++-- take_last_test.go | 23 +++++++++++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/take_last.go b/take_last.go index 97b65c5..b47b72a 100644 --- a/take_last.go +++ b/take_last.go @@ -18,12 +18,16 @@ type takeLastIterator[T any] struct { // itb := gcf.FromSlice([]{1, 2, 3}) // itb = gcf.TakeLast(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 TakeLast[T any](itb Iterable[T], count int) Iterable[T] { + if count < 0 { + panic("count for TakeLast must not be negative.") + } if isEmpty(itb) { return orEmpty(itb) } - if count < 1 { + if count == 0 { return empty[T]() } return &takeLastIterable[T]{itb, count} diff --git a/take_last_test.go b/take_last_test.go index 38f6c6c..48b3474 100644 --- a/take_last_test.go +++ b/take_last_test.go @@ -14,9 +14,10 @@ func TestTakeLast(t *testing.T) { count int } tests := []struct { - name string - args args - want []int + name string + args args + want []int + wantPanic bool }{ { name: "take last 1 from slice 3", @@ -64,7 +65,7 @@ func TestTakeLast(t *testing.T) { itb: gcf.FromSlice([]int{1, 2, 3}), count: -1, }, - want: []int{}, + wantPanic: true, }, { name: "nil Iterable", @@ -74,9 +75,23 @@ func TestTakeLast(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.TakeLast(tt.args.itb, tt.args.count) + }) + return + } itb := gcf.TakeLast(tt.args.itb, tt.args.count) s := gcf.ToSlice(itb) assert.Equal(t, tt.want, s)