Skip to content

Commit

Permalink
Merge branch 'ka/slice-last-n'
Browse files Browse the repository at this point in the history
  • Loading branch information
kazhuravlev committed May 19, 2024
2 parents 3511893 + d35bd9e commit 4a209d8
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
28 changes: 28 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -742,3 +742,31 @@ func SliceShuffleCopy[T any](in []T) []T {

return res
}

// SliceLastN return up to last n elements from input slice in original order.
func SliceLastN[T any](in []T, n int) []T {
if n < 0 {
panic("n should be greater than 0")
}

inLen := len(in)

if inLen == 0 || n == 0 {
return make([]T, 0)
}

if inLen == n {
res := make([]T, n)
copy(res, in)

return res
}

n = Min(inLen, n)
res := make([]T, n)
for i := n - 1; i >= 0; i-- {
res[i] = in[inLen-n+i]
}

return res
}
46 changes: 46 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1816,3 +1816,49 @@ func TestSliceShuffleCopy(t *testing.T) {
})
}
}

func TestSliceLastN(t *testing.T) {
table := []struct {
in []int
n int
exp []int
}{
{
in: nil,
n: 10,
exp: []int{},
},
{
in: nil,
n: 0,
exp: []int{},
},
{
in: []int{10},
n: 0,
exp: []int{},
},
{
in: []int{10},
n: 1,
exp: []int{10},
},
{
in: []int{10},
n: 6,
exp: []int{10},
},
{
in: []int{10, 20, 30, 40, 50},
n: 2,
exp: []int{40, 50},
},
}

for _, row := range table {
t.Run("", func(t *testing.T) {
res := just.SliceLastN(row.in, row.n)
require.Equal(t, row.exp, res)
})
}
}

0 comments on commit 4a209d8

Please sign in to comment.