Skip to content

slices: add Map #66333

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

Closed
wants to merge 1 commit into from
Closed
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
9 changes: 9 additions & 0 deletions src/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,3 +474,12 @@ func Concat[S ~[]E, E any](slices ...S) S {
}
return newslice
}

// Map returns a new slice containing the result of applying fn to each element of s.
func Map[S ~[]E, E, R any](s S, fn func(E) R) []R {
var result []R
for _, item := range s {
result = append(result, fn(item))
}
return result
}
27 changes: 27 additions & 0 deletions src/slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"internal/testenv"
"math"
. "slices"
"strconv"
"strings"
"testing"
)
Expand Down Expand Up @@ -1335,3 +1336,29 @@ func TestConcat_too_large(t *testing.T) {
}
}
}

func TestMap(t *testing.T) {
s1 := []int{1, 2, 3, 4, 5}
got1 := Map(s1, func(n int) int { return n * 2 })
want1 := []int{2, 4, 6, 8, 10}
if !Equal(want1, got1) {
t.Errorf("Map(%v) = %v, want %v", s1, got1, want1)
}

s2 := []int{1, 2, 3, 4, 5}
got2 := Map(s2, strconv.Itoa)
want2 := []string{"1", "2", "3", "4", "5"}
if !Equal(want2, got2) {
t.Errorf("Map(%v) = %v, want %v", s2, got2, want2)
}

s3 := []string{"1", "2", "3", "4", "5"}
type T struct {
A string
}
got3 := Map(s3, func(s string) T { return T{s} })
want3 := []T{{"1"}, {"2"}, {"3"}, {"4"}, {"5"}}
if !Equal(want3, got3) {
t.Errorf("Map(%v) = %v, want %v", s3, got3, want3)
}
}