-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |