diff options
-rw-r--r-- | src/gobang.go | 24 | ||||
-rw-r--r-- | tests/gobang.go | 93 |
2 files changed, 117 insertions, 0 deletions
diff --git a/src/gobang.go b/src/gobang.go index 2985d19..1826a5f 100644 --- a/src/gobang.go +++ b/src/gobang.go @@ -65,6 +65,30 @@ var ( +func MapIndexed[A any, B any](fn func(A, int) B, coll []A) []B { + out := make([]B, len(coll)) + for i, x := range coll { + out[i] = fn(x, i) + } + return out +} + +func Map[A any, B any](fn func(A) B, coll []A) []B { + return MapIndexed(func(x A, _ int) B { + return fn(x) + }, coll) +} + +func Filter[A any](fn func(A) bool, coll []A) []A { + out := []A{} + for _, x := range coll { + if fn(x) { + out = append(out, x) + } + } + return out +} + func PanicIf(err error) { if err != nil { panic(err) diff --git a/tests/gobang.go b/tests/gobang.go index 32f6d99..56e3978 100644 --- a/tests/gobang.go +++ b/tests/gobang.go @@ -15,6 +15,96 @@ import ( +func test_MapIndexed() { + TestStart("MapIndexed()") + + Testing("empty array", func() { + noop := func(s string, i int) string { + return s + } + + arr := []string{} + TAssertEqual(MapIndexed(noop, arr), arr) + }) + + Testing("replace content with index", func() { + index := func(s string, i int) int { + return i + } + + TAssertEqual( + MapIndexed(index, []string{"a", "b", "c"}), + []int{0, 1, 2}, + ) + }) + + Testing("a computed value", func() { + fn := func(x int, i int) int { + return x + i + } + + TAssertEqual( + MapIndexed(fn, []int{1, 2, 3, 4, 5}), + []int{1, 3, 5, 7, 9}, + ) + }) +} + +func test_Map() { + TestStart("Map()") + + Testing("empty array", func() { + noop := func(s string) string { + return s + } + + arr := []string{} + TAssertEqual(Map(noop, arr), arr) + }) + + Testing("a derived value", func() { + appendBang := func(s string) string { + return s + "!" + } + + TAssertEqual( + Map(appendBang, []string{"a", "b", "c"}), + []string{"a!", "b!", "c!"}, + ) + }) +} + +func test_Filter() { + TestStart("Filter()") + + fn := func(i int) bool { + return i < 10 + } + + + Testing("empty array", func() { + arr := []int{} + TAssertEqual(Filter(fn, arr), arr) + }) + + Testing("filters everything", func() { + arr := []int{10, 11, 12, 13, 14, 15} + TAssertEqual(Filter(fn, arr), []int{}) + }) + + Testing("filters nothing", func() { + arr := []int{1, 2, 3, 4, 5} + TAssertEqual(Filter(fn, arr), arr) + }) + + Testing("filters some", func() { + TAssertEqual( + Filter(fn, []int{8, 9, 10, 11, 12, 0, 13}), + []int{8, 9, 0}, + ) + }) +} + func test_PanicIf() { TestStart("PanicIf()") @@ -1354,6 +1444,9 @@ func test_setHostname() { func MainTest() { Init() + test_MapIndexed() + test_Map() + test_Filter() test_PanicIf() test_Must() test_Clamp() |