Skip to content

Commit

Permalink
chore: add maps.Flip
Browse files Browse the repository at this point in the history
  • Loading branch information
zostay committed Sep 3, 2024
1 parent 55a10dd commit 605e577
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions maps/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,14 @@ func KVs[K comparable, V any](in map[K]V) []any {
}
return out
}

// Flip will return a new map with the keys and values of the input map flipped.
// That is, the keys of the input map will be the values of the output map and
// the values of the input map will be the keys of the output map.
func Flip[K comparable, V comparable](in map[K]V) map[V]K {
out := make(map[V]K, len(in))
for k, v := range in {
out[v] = k
}
return out
}
22 changes: 22 additions & 0 deletions maps/transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,25 @@ func TestKVs(t *testing.T) {
}
}
}

func TestFlip(t *testing.T) {
t.Parallel()

a := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}

vks := maps.Flip(a)
assert.Len(t, vks, len(a))
for k, v := range a {
assert.Contains(t, vks, v)
assert.Equal(t, k, vks[v])
}

for k, v := range vks {
assert.Contains(t, a, v)
assert.Equal(t, k, a[v])
}
}

0 comments on commit 605e577

Please sign in to comment.