From a4364b555a903fe74cad2cd6d57bf252a890f4c5 Mon Sep 17 00:00:00 2001 From: Matt Oestreich <21092343+oze4@users.noreply.github.com> Date: Fri, 16 Aug 2024 07:59:50 -0500 Subject: [PATCH] Add At func --- README.md | 13 +++++++++++++ at.go | 22 ++++++++++++++++++++++ jslice_test.go | 20 ++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 at.go diff --git a/README.md b/README.md index 3bcd989..e5cb0f7 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,19 @@ jslice.Unshift(&s, 1) // s == []int{1,2,3,4,5} ``` +## At + +At takes an integer value and returns the item at that index, allowing for **positive** _and_ **negative** integers. Negative integers +count back from the last item in the array. + +**NOTE**: If the provided index is negative, and it's absolute value is greater than the length of the array, we return the first item (index 0) in the array. + +```go +s := []int{1,2,3,4,5} +r := jslice.At(s, -3) +// r == 3 +``` + diff --git a/at.go b/at.go new file mode 100644 index 0000000..8edde99 --- /dev/null +++ b/at.go @@ -0,0 +1,22 @@ +package jslice + +import "math" + +// At takes an integer value and returns the item at that index, +// allowing for positive and negative integers. Negative integers +// count back from the last item in the array. +// +// If the provided index is negative but it's absolute value +// is greater than the length of the array, we return the first +// item (index 0) in the array. +func At[T any](s []T, index int) T { + size := len(s) + if index < 0 { + if int(math.Abs(float64(index))) > size { + index = 0 + } else { + index = size + index + } + } + return s[index] +} diff --git a/jslice_test.go b/jslice_test.go index 7d920bc..1fa49d5 100644 --- a/jslice_test.go +++ b/jslice_test.go @@ -465,6 +465,26 @@ func TestUnshift(t *testing.T) { t.Log(s) } +func TestAt_NegativeIndex(t *testing.T) { + EXPECT_VAL := 5 + s := []int{1, 2, 3, 4, 5} + r := jslice.At(s, -1) + if r != EXPECT_VAL { + t.Fatalf("Expected=%d | Got=%d\n", EXPECT_VAL, r) + } + t.Log(r) +} + +func TestAt_PositiveIndex(t *testing.T) { + EXPECT_VAL := 2 + s := []int{1, 2, 3, 4, 5} + r := jslice.At(s, 1) + if r != EXPECT_VAL { + t.Fatalf("Expected=%d | Got=%d\n", EXPECT_VAL, r) + } + t.Log(r) +} + // ************************************************************** func TestTest(t *testing.T) {