Skip to content

Commit

Permalink
#18. Add ArrayCountValues + change file names
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman committed Mar 19, 2019
1 parent 5deadfe commit 4449e4c
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,11 @@ map[int]string{
*/
```

#### Count all the values of an array/slice
```go
pgo.ArrayCountValues([]string{"foo", "bar", "foo", "baz", "bar", "bar"}) // map[string]int{"foo": 2, "bar": 3, "baz": 1}

pgo.ArrayCountValues([]float64{3.14159, 43.03, 8, 3.14159, 43.02, 8}) // map[float64]int{3.14159: 2, 8: 2, 43.03: 1, 43.02: 1}
```

See more examples in *_test.go files.
13 changes: 13 additions & 0 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,16 @@ func ArrayCombine(keys interface{}, values interface{}) map[interface{}]interfac

return resultMap
}

// ArrayCountValues counts all the values of an array/slice
func ArrayCountValues(array interface{}) map[interface{}]int {
res := make(map[interface{}]int)

s := reflect.ValueOf(array)
len := s.Len()
for i := 0; i < len; i++ {
res[s.Index(i).Interface()]++
}

return res
}
22 changes: 22 additions & 0 deletions array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,25 @@ func TestArrayCombine(t *testing.T) {
}
}
}

var testArrayCountValues = []struct {
values interface{}
result interface{}
}{
{[]string{"foo", "bar", "foo", "baz", "bar", "bar"}, map[string]int{"foo": 2, "bar": 3, "baz": 1}},
{[]int{3, 43, 8, 43, 8}, map[int]int{43: 2, 8: 2, 3: 1}},
{[]float64{3.14159, 43.03, 8, 3.14159, 43.02, 8}, map[float64]int{3.14159: 2, 8: 2, 43.03: 1, 43.02: 1}},
}

func TestArrayCountValues(t *testing.T) {
for _, object := range testArrayCountValues {
res := pgo.ArrayCountValues(object.values)

m := reflect.ValueOf(object.result)
for k, v := range res {
if m.MapIndex(reflect.ValueOf(k)).Interface() != v {
t.Fatalf("want %d, got %d", m.MapIndex(reflect.ValueOf(k)).Interface(), v)
}
}
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 4449e4c

Please sign in to comment.