Skip to content

Commit

Permalink
feat: add slicesx.Map extension
Browse files Browse the repository at this point in the history
  • Loading branch information
francesconi committed Jul 23, 2024
1 parent 559127a commit 1c2890c
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
4 changes: 2 additions & 2 deletions slicesx/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ func TestFilter(t *testing.T) {
{Category: "Medicine", Laureate: "Julius Axelrod"},
}

filtered := Filter(nobelPrizes, func(l nobelPrize) bool {
return l.Category == "Medicine"
filtered := Filter(nobelPrizes, func(n nobelPrize) bool {
return n.Category == "Medicine"
})

assert.EqualValues(t, []nobelPrize{
Expand Down
9 changes: 9 additions & 0 deletions slicesx/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package slicesx

func Map[S ~[]E, E, T any](s S, f func(E) T) []T {
t := make([]T, len(s))
for i, e := range s {
t[i] = f(e)
}
return t
}
42 changes: 42 additions & 0 deletions slicesx/map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package slicesx

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestMap(t *testing.T) {
type nobelPrize struct {
Category string
Laureate string
}
nobelPrizes := []nobelPrize{
{Category: "Chemistry", Laureate: "Luis Leloir"},
{Category: "Economics", Laureate: "Paul Samuelson"},
{Category: "Literature", Laureate: "Aleksandr Solzhenitsyn"},
{Category: "Peace", Laureate: "Norman Borlaug"},
{Category: "Physics", Laureate: "Hannes Alfvén"},
{Category: "Physics", Laureate: "Louis Néel"},
{Category: "Medicine", Laureate: "Sir Bernard Katz"},
{Category: "Medicine", Laureate: "Ulf von Euler"},
{Category: "Medicine", Laureate: "Julius Axelrod"},
}

lowered := Map(nobelPrizes, func(n nobelPrize) string {
return strings.ToLower(n.Laureate)
})

assert.EqualValues(t, []string{
"luis leloir",
"paul samuelson",
"aleksandr solzhenitsyn",
"norman borlaug",
"hannes alfvén",
"louis néel",
"sir bernard katz",
"ulf von euler",
"julius axelrod",
}, lowered)
}

0 comments on commit 1c2890c

Please sign in to comment.