| 1 |
package higherorder |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"strings" |
| 6 |
"testing" |
| 7 |
) |
| 8 |
|
| 9 |
func Test_Foldl(t *testing.T) { |
| 10 |
x := Foldl(func(a, b int) int { |
| 11 |
return a + b |
| 12 |
}, 0, []int{1, 2, 3}) |
| 13 |
|
| 14 |
const expect = 6 |
| 15 |
if x != expect { |
| 16 |
t.Errorf("Expected %d, got %d", expect, x) |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
func Test_Foldr(t *testing.T) { |
| 21 |
x := Foldl(func(a, b int) int { |
| 22 |
return a - b |
| 23 |
}, 6, []int{1, 2, 3}) |
| 24 |
|
| 25 |
const expect = 0 |
| 26 |
if x != expect { |
| 27 |
t.Errorf("Expected %d, got %d", expect, x) |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
func Test_Map(t *testing.T) { |
| 32 |
{ |
| 33 |
// Map over ints, returning the square of each int. |
| 34 |
// (Take ints, return ints.) |
| 35 |
x := Map(func(a int) int { |
| 36 |
return a * a |
| 37 |
}, []int{2, 3, 4}) |
| 38 |
|
| 39 |
expected := []int{4, 9, 16} |
| 40 |
for i, v := range x { |
| 41 |
if v != expected[i] { |
| 42 |
t.Errorf("Index %d: expected %d, got %d", i, expected[i], v) |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
{ |
| 47 |
// Map over strings, returning the length of each string. |
| 48 |
// (Take ints, return strings.) |
| 49 |
x := Map(func(a string) int { |
| 50 |
return len([]rune(a)) |
| 51 |
}, []string{"one", "two", "three"}) |
| 52 |
|
| 53 |
expected := []int{3, 3, 5} |
| 54 |
for i, v := range x { |
| 55 |
if v != expected[i] { |
| 56 |
t.Errorf("Index %d: expected %d, got %d", i, expected[i], v) |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func Test_Filter(t *testing.T) { |
| 63 |
t.Run("with string slices", func(t *testing.T) { |
| 64 |
got := Filter(func(a string) bool { |
| 65 |
return strings.HasPrefix(a, "t") |
| 66 |
}, []string{"one", "two", "three"}) |
| 67 |
|
| 68 |
want := []string{"two", "three"} |
| 69 |
|
| 70 |
if !reflect.DeepEqual(got, want) { |
| 71 |
t.Errorf("Expected %v, got %v", want, got) |
| 72 |
} |
| 73 |
}) |
| 74 |
|
| 75 |
t.Run("with int slices", func(t *testing.T) { |
| 76 |
got := Filter(func(a int) bool { |
| 77 |
return a%2 == 0 |
| 78 |
}, []int{1, 2, 3, 4, 5}) |
| 79 |
|
| 80 |
want := []int{2, 4} |
| 81 |
|
| 82 |
if !reflect.DeepEqual(got, want) { |
| 83 |
t.Errorf("Expected %v, got %v", want, got) |
| 84 |
} |
| 85 |
}) |
| 86 |
} |