Skip to content

Commit

Permalink
Add SliceFrom/To mapper operations
Browse files Browse the repository at this point in the history
  • Loading branch information
Joseph Fourny committed Dec 13, 2023
1 parent b72fd45 commit ad2e7e4
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions pkg/mapper/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,24 @@ func Decrement[E constraint.RealNumber](step E) func(E) E {
return e - step
}
}

// SliceFrom returns a function that accepts a slice of any type E and returns a slice of the same type containing all elements from the provided `start` index to the end of the slice.
func SliceFrom[E any](start int) func([]E) []E {
return func(s []E) []E {
return s[start:]
}
}

// SliceTo returns a function that accepts a slice of any type E and returns a slice of the same type containing all elements from the start of the slice up to, but excluding, the provided `end` index.
func SliceTo[E any](end int) func([]E) []E {
return func(s []E) []E {
return s[:end]
}
}

// SliceFromTo returns a function that accepts a slice of any type E and returns a slice of the same type containing all elements from the provided `start` index up to, but excluding, the provided `end` index.
func SliceFromTo[E any](start int, end int) func([]E) []E {
return func(s []E) []E {
return s[start:end]
}
}
28 changes: 28 additions & 0 deletions pkg/mapper/mapper_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mapper

import (
"slices"
"testing"

"github.com/jpfourny/papaya/pkg/pointer"
Expand Down Expand Up @@ -473,3 +474,30 @@ func TestDecrement(t *testing.T) {
t.Errorf("Decrement(2)(42) = %#v; want %#v", got, want)
}
}

func TestSliceFrom(t *testing.T) {
m := SliceFrom[int](1)
got := m([]int{1, 2, 3})
want := []int{2, 3}
if !slices.Equal(got, want) {
t.Errorf("SliceFrom(1)([1, 2, 3]) = %#v; want %#v", got, want)
}
}

func TestSliceTo(t *testing.T) {
m := SliceTo[int](2)
got := m([]int{1, 2, 3})
want := []int{1, 2}
if !slices.Equal(got, want) {
t.Errorf("SliceTo(2)([1, 2, 3]) = %#v; want %#v", got, want)
}
}

func TestSliceFromTo(t *testing.T) {
m := SliceFromTo[int](1, 2)
got := m([]int{1, 2, 3})
want := []int{2}
if !slices.Equal(got, want) {
t.Errorf("SliceFromTo(1, 2)([1, 2, 3]) = %#v; want %#v", got, want)
}
}

0 comments on commit ad2e7e4

Please sign in to comment.