From d35bd9ef2e77ae5b552f6f0ea1808593144ca7b4 Mon Sep 17 00:00:00 2001 From: Kirill Zhuravlev Date: Sun, 19 May 2024 12:59:57 +0200 Subject: [PATCH] add new slice helper --- slice.go | 28 ++++++++++++++++++++++++++++ slice_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/slice.go b/slice.go index fc9e11d..b2907aa 100644 --- a/slice.go +++ b/slice.go @@ -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 +} diff --git a/slice_test.go b/slice_test.go index 50ac4bf..eb61bef 100644 --- a/slice_test.go +++ b/slice_test.go @@ -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) + }) + } +}