Skip to content

Commit

Permalink
Merge 7cd9a47 into 174b145
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jul 31, 2019
2 parents 174b145 + 7cd9a47 commit b4fd2ef
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,4 @@ problems from
* [Day 338](https://github.com/vaskoz/dailycodingproblem-go/issues/675)
* [Day 339](https://github.com/vaskoz/dailycodingproblem-go/issues/676)
* [Day 340](https://github.com/vaskoz/dailycodingproblem-go/issues/679)
* [Day 342](https://github.com/vaskoz/dailycodingproblem-go/issues/682)
14 changes: 14 additions & 0 deletions day342/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package day342

// Reduce is a function that takes in an array,
// a combining function, and an initial value
// and builds up a result by calling the combining
// function on each element of the array, left to right.
func Reduce(lst []interface{},
reducer func(a, b interface{}) interface{},
initial interface{}) interface{} {
for _, v := range lst {
initial = reducer(initial, v)
}
return initial
}
48 changes: 48 additions & 0 deletions day342/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package day342

import (
"fmt"
"testing"
)

// nolint
var testcases = []struct {
lst []interface{}
reducer func(a, b interface{}) interface{}
initial interface{}
expected interface{}
}{
{
[]interface{}{1, 2, 3, 4, 5, 6},
func(a, b interface{}) interface{} {
return a.(int) + b.(int)
},
0,
21,
},
{
[]interface{}{"hello", "world", "goodbye"},
func(a, b interface{}) interface{} {
return fmt.Sprintf("%s %s", a, b)
},
"begin",
"begin hello world goodbye",
},
}

func TestReduce(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := Reduce(tc.lst, tc.reducer, tc.initial); result != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

func BenchmarkReduce(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
Reduce(tc.lst, tc.reducer, tc.initial)
}
}
}

0 comments on commit b4fd2ef

Please sign in to comment.