-
Notifications
You must be signed in to change notification settings - Fork 4
/
reduce_test.go
73 lines (61 loc) · 1.72 KB
/
reduce_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package hoff
import (
"context"
"fmt"
)
const multiplierKey = contextKey("multiplier")
const divisorKey = contextKey("divisor")
func sumInts(acc int, elem int, _ int) int {
return acc + elem
}
func sumIntsError(acc int, elem int, _ int) (int, error) {
if elem == 4 {
return acc, fmt.Errorf("invalid element (4) encountered")
}
return acc + elem, nil
}
func sumIntsCtxMultiplier(ctx context.Context, acc int, elem int, _ int) int {
m := ctx.Value(multiplierKey).(int)
return acc + (elem * m)
}
func sumIntsCtxDividerError(ctx context.Context, acc int, elem int, _ int) (int, error) {
m := ctx.Value(divisorKey).(int)
if m == 0 {
return acc, fmt.Errorf("division by zero")
}
return acc + (elem / m), nil
}
func ExampleReduce() {
a := []int{1, 2, 3, 4, 5}
total := Reduce(a, sumInts, 0)
fmt.Println(total)
// Output: 15
}
func ExampleReduceError() {
a := []int{1, 2, 3}
fmt.Println(ReduceError(a, sumIntsError, 0))
// Output: 6 <nil>
}
func ExampleReduceError_error() {
a := []int{1, 2, 3, 4, 5}
fmt.Println(ReduceError(a, sumIntsError, 0))
// Output: 6 invalid element (4) encountered
}
func ExampleReduceContext() {
ctx := context.WithValue(context.Background(), multiplierKey, 2)
a := []int{1, 2, 3, 4, 5}
fmt.Println(ReduceContext(ctx, a, sumIntsCtxMultiplier, 0))
// Output: 30
}
func ExampleReduceContextError() {
ctx := context.WithValue(context.Background(), divisorKey, 2)
a := []int{2, 4, 6}
fmt.Println(ReduceContextError(ctx, a, sumIntsCtxDividerError, 0))
// Output: 6 <nil>
}
func ExampleReduceContextError_error() {
ctx := context.WithValue(context.Background(), divisorKey, 0)
a := []int{2, 4, 6}
fmt.Println(ReduceContextError(ctx, a, sumIntsCtxDividerError, 0))
// Output: 0 division by zero
}