File: higherorder_test.go

package info (click to toggle)
golang-github-charmbracelet-x 0.0~git20240809.9ab0ca0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,004 kB
  • sloc: sh: 55; makefile: 5
file content (86 lines) | stat: -rw-r--r-- 1,709 bytes parent folder | download
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
74
75
76
77
78
79
80
81
82
83
84
85
86
package higherorder

import (
	"reflect"
	"strings"
	"testing"
)

func Test_Foldl(t *testing.T) {
	x := Foldl(func(a, b int) int {
		return a + b
	}, 0, []int{1, 2, 3})

	const expect = 6
	if x != expect {
		t.Errorf("Expected %d, got %d", expect, x)
	}
}

func Test_Foldr(t *testing.T) {
	x := Foldl(func(a, b int) int {
		return a - b
	}, 6, []int{1, 2, 3})

	const expect = 0
	if x != expect {
		t.Errorf("Expected %d, got %d", expect, x)
	}
}

func Test_Map(t *testing.T) {
	{
		// Map over ints, returning the square of each int.
		// (Take ints, return ints.)
		x := Map(func(a int) int {
			return a * a
		}, []int{2, 3, 4})

		expected := []int{4, 9, 16}
		for i, v := range x {
			if v != expected[i] {
				t.Errorf("Index %d: expected %d, got %d", i, expected[i], v)
			}
		}
	}
	{
		// Map over strings, returning the length of each string.
		// (Take ints, return strings.)
		x := Map(func(a string) int {
			return len([]rune(a))
		}, []string{"one", "two", "three"})

		expected := []int{3, 3, 5}
		for i, v := range x {
			if v != expected[i] {
				t.Errorf("Index %d: expected %d, got %d", i, expected[i], v)
			}
		}
	}
}

func Test_Filter(t *testing.T) {
	t.Run("with string slices", func(t *testing.T) {
		got := Filter(func(a string) bool {
			return strings.HasPrefix(a, "t")
		}, []string{"one", "two", "three"})

		want := []string{"two", "three"}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("Expected %v, got %v", want, got)
		}
	})

	t.Run("with int slices", func(t *testing.T) {
		got := Filter(func(a int) bool {
			return a%2 == 0
		}, []int{1, 2, 3, 4, 5})

		want := []int{2, 4}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("Expected %v, got %v", want, got)
		}
	})
}