23 lines
950 B
Go
23 lines
950 B
Go
// Package sieve provides generic, dependency-free collection helpers that the
|
|
// standard library slices and maps packages lack.
|
|
//
|
|
// Every function is eager and never modifies its input. Results never share a
|
|
// backing array with the input, so changing or appending to a result leaves the
|
|
// caller's slice unchanged. Callbacks run once per element, in input order.
|
|
// Nil or empty input yields a non-nil empty slice or map, so encoding/json
|
|
// writes [] or {} rather than null.
|
|
package sieve
|
|
|
|
// Map returns a new slice holding f applied to each element of s, in order.
|
|
// f is called once per element. A nil or empty s yields a non-nil empty slice.
|
|
//
|
|
// Map is also the pluck operation: pass an accessor func to extract one field
|
|
// from every element, for example the titles of a slice of posts.
|
|
func Map[S ~[]T, T, U any](s S, f func(T) U) []U {
|
|
out := make([]U, 0, len(s))
|
|
for _, v := range s {
|
|
out = append(out, f(v))
|
|
}
|
|
return out
|
|
}
|