From 515dedae1c04f1f23ed55e450a95f2d3a2c1b451 Mon Sep 17 00:00:00 2001 From: Arthur Kushman Date: Wed, 15 Jun 2022 20:34:02 +0300 Subject: [PATCH] #20: Add ArrayValues impl (#64) --- README.md | 11 +++++++++++ array.go | 12 ++++++++++++ array_test.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/README.md b/README.md index 0493356..852ce16 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Go library for PHP community with convenient functions * [ArrayIntersect](#user-content-arrayintersect) * [ArrayMin/ArrayMax](#user-content-arrayminarraymax) * [ArrayUnique](#user-content-arrayunique) + * [ArrayValues](#user-content-arrayvalues) * [Range](#user-content-range) * [EqualSlices](#user-content-equalslices) * [Collections](#user-content-collections) @@ -375,6 +376,16 @@ res = pgo.ArrayUnique([]string{"foo", "bar", "foo", "bar"}) // []string{"bar", " ``` Note: order is not guaranteed +#### ArrayValues + +return all the values of map as a slice of values with corresponding type + +```go +res = pgo.ArrayValues(map[string]int{"a": 1, "b": 2, "c": 3}) // []int{1, 2, 3} + +res = pgo.ArrayValues(map[int]float64{1: 123.33, 2: 22, 3: 123.33}) // []float64{22, 123.33, 123.33} +``` + #### Range creates an int slice of min to max range diff --git a/array.go b/array.go index 32b4eb3..0596469 100644 --- a/array.go +++ b/array.go @@ -340,3 +340,15 @@ func ArrayUnique[T comparable](a []T) []T { return s } + +// ArrayValues Return all the values of map as a slice of values with corresponding type +func ArrayValues[K, V comparable](a map[K]V) []V { + s := make([]V, len(a)) + var i uint64 + for _, v := range a { + s[i] = v + i++ + } + + return s +} diff --git a/array_test.go b/array_test.go index 927c8f9..71bc1a4 100644 --- a/array_test.go +++ b/array_test.go @@ -500,3 +500,33 @@ func TestUnique(t *testing.T) { assert.Equal(t, res, v.res) } } + +var testArrayValues = []struct { + a interface{} + res interface{} +}{ + {map[string]int{"a": 1, "b": 2, "c": 3}, []int{1, 2, 3}}, + {map[string]int{"a": 1, "b": 2, "c": 2, "d": 3, "e": 4, "f": 4}, []int{1, 2, 2, 3, 4, 4}}, + {map[int]string{2: "foo", 1: "bar", 123: "foo", -12: "bar"}, []string{"bar", "bar", "foo", "foo"}}, + {map[int]float64{1: 123.33, 2: 22, 3: 123.33}, []float64{22, 123.33, 123.33}}, + {map[int]float64{}, []float64{}}, +} + +func TestArrayValues(t *testing.T) { + for _, v := range testArrayValues { + var res interface{} + switch v.a.(type) { + case map[string]int: + res = pgo.ArrayValues(v.a.(map[string]int)) + sort.Ints(res.([]int)) + case map[int]float64: + res = pgo.ArrayValues(v.a.(map[int]float64)) + sort.Float64s(res.([]float64)) + case map[int]string: + res = pgo.ArrayValues(v.a.(map[int]string)) + sort.Strings(res.([]string)) + } + + assert.Equal(t, res, v.res) + } +}