Skip to content

Commit

Permalink
#20: Add ArrayValues impl (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman authored Jun 15, 2022
1 parent 01912a9 commit 515deda
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
30 changes: 30 additions & 0 deletions array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 515deda

Please sign in to comment.