feat: maps map (#9)

Co-authored-by: Ruidy <rnemausat@newstore.com>
This commit is contained in:
Ruidy 2022-01-27 11:15:33 -04:00 committed by GitHub
parent c0a8ecea0c
commit f73905ddb0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 58 additions and 2 deletions

View file

@ -10,6 +10,6 @@ func chaining() int {
Filter(func(n int) bool { return n%2 == 0 }).
// square every number in the slice
Map(func(n int) int { return n * n }).
// reduce to the sum
// reduce the slice to its sum
Reduce(func(n, acc int) int { return n + acc }, 0)
}

View file

@ -10,7 +10,7 @@ func filterMapReduce() int {
evens := u.Filter(numbers, func(n int) bool { return n%2 == 0 })
// square every number in the slice
squares := u.Map(evens, func(n int) int { return n * n })
// reduce to the sum
// reduce the slice to its sum
res := u.Reduce(squares, func(n, acc int) int { return n + acc }, 0)
return res

16
maps/map.go Normal file
View file

@ -0,0 +1,16 @@
package maps
type M[K comparable, V any] map[K]V
// Map produces a new slice of values by mapping each value in the slice through
// a transform function.
func Map[K, Q comparable, V, W any](m M[K, V], f func(K, V) M[Q, W]) M[Q, W] {
res := make(M[Q, W], len(m))
for k, v := range m {
mm := f(k, v)
for k2, v2 := range mm {
res[k2] = v2
}
}
return res
}

40
maps/map_test.go Normal file
View file

@ -0,0 +1,40 @@
package maps_test
import (
"testing"
"github.com/stretchr/testify/assert"
u "github.com/rjNemo/underscore"
m "github.com/rjNemo/underscore/maps"
)
func TestMap(t *testing.T) {
scores := m.M[string, int]{
"alice": 0,
"bob": 10,
"clara": 7,
"david": 23,
}
hasWon := func(key string, value int) m.M[string, bool] { return m.M[string, bool]{key: value > 21} }
want := m.M[string, bool]{
"alice": false,
"bob": false,
"clara": false,
"david": true}
assert.Equal(t, want, m.Map(scores, hasWon))
}
func TestMapSlices(t *testing.T) {
scores := []m.M[string, int]{
{"score": 0},
{"score": 10},
{"score": 7},
{"score": 23},
}
hasWon := func(s m.M[string, int]) bool { return s["score"] > 21 }
want := []bool{false, false, false, true}
assert.Equal(t, want, u.Map(scores, hasWon))
}