Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 342
Good morning! Here's your coding interview problem for today.

This problem was asked by Stripe.

`reduce` (also known as `fold`) 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. For example, we can write `sum()` in terms of `reduce`:
```
def add(a, b):
    return a + b

def sum(lst):
    return reduce(lst, add, 0)
```
This should call `add` on the initial value with the first element of the array, and then the result of that with the second element of the array, and so on until we reach the end, when we return the sum of the array.

Implement your own version of `reduce`.

Pull request description:
Day342
Resolves #682.

Patch:
diff --git a/README.md b/README.md
index 2ab56a5..3e2ccd9 100644
--- a/README.md
+++ b/README.md
@@ -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)
diff --git a/day342/problem.go b/day342/problem.go
new file mode 100644
index 0000000..da1d5d5
--- /dev/null
+++ b/day342/problem.go
@@ -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
+}


Test patch:
diff --git a/day342/problem_test.go b/day342/problem_test.go
new file mode 100644
index 0000000..413f583
--- /dev/null
+++ b/day342/problem_test.go
@@ -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)
+		}
+	}
+}