Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add At func #9

Merged
merged 1 commit into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```




Expand Down
22 changes: 22 additions & 0 deletions at.go
Original file line number Diff line number Diff line change
@@ -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]
}
20 changes: 20 additions & 0 deletions jslice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down