Skip to content

Commit

Permalink
[TASK] TRK-1974 Add map reindex function (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skandalik authored Oct 31, 2023
1 parent a858114 commit eb125f1
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
12 changes: 12 additions & 0 deletions gofp/reindex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package gofp

// Reindex apply a function to all elements on an map
func Reindex[InK, OutK comparable, InV, OutV any](m map[InK]InV, fn func(InK, InV) (OutK, OutV)) (res map[OutK]OutV) {
res = make(map[OutK]OutV, len(m))
for k, v := range m {
rK, rV := fn(k, v)
res[rK] = rV
}

return
}
91 changes: 91 additions & 0 deletions gofp/reindex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package gofp_test

import (
"strconv"
"testing"

. "github.com/msales/gox/gofp"
)

func TestReindex_Int64ToIn32(t *testing.T) {
got := Reindex(map[int64]int64{1: 1, 2: 2, 3: 3}, func(key, val int64) (int32, int32) {
return int32(key), int32(val)
})

want := map[int32]int32{1: 1, 2: 2, 3: 3}

if len(want) != len(got) {
t.Errorf("Got %+v, want %+v", got, want)
return
}

for k, v := range want {
if v != got[k] {
t.Errorf("Got %+v, want %+v", got, want)
}
}
}

func TestReindex_StringToStruct(t *testing.T) {
got := Reindex(map[string]string{
"1": "1",
"2": "2",
"3": "3",
}, func(key, val string) (string, testID) {
id, _ := strconv.ParseInt(val, 10, 64)
return key, testID{ID: id}
})

want := map[string]testID{
"1": {ID: 1},
"2": {ID: 2},
"3": {ID: 3},
}

if len(want) != len(got) {
t.Errorf("Got %+v, want %+v", got, want)
return
}

for k, v := range want {
if v != got[k] {
t.Errorf("Got %+v, want %+v", got, want)
}
}
}

func BenchmarkReindex_Int64ToIn32(b *testing.B) {
original := map[int64]int64{
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
}
b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
Reindex(original, func(key, val int64) (int32, int32) {
return int32(key), int32(val)
})
}
}

func BenchmarkReindex_StringToStruct(b *testing.B) {
original := map[string]string{
"1": "1",
"2": "2",
"3": "2",
}
b.ReportAllocs()
b.ResetTimer()

for i := 0; i < b.N; i++ {
Reindex(original, func(key, val string) (string, testID) {
id, _ := strconv.ParseInt(val, 10, 64)
return key, testID{ID: id}
})
}
}

0 comments on commit eb125f1

Please sign in to comment.