From 715f2d8296b7236537d6686708e0628d42fd096a Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 2 Mar 2024 14:29:28 -0500 Subject: [PATCH] Iteration done --- learn_go_with_tests/iteration/go.mod | 3 ++ learn_go_with_tests/iteration/repeat.go | 12 ++++++ learn_go_with_tests/iteration/repeat_test.go | 41 ++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 learn_go_with_tests/iteration/go.mod create mode 100644 learn_go_with_tests/iteration/repeat.go create mode 100644 learn_go_with_tests/iteration/repeat_test.go diff --git a/learn_go_with_tests/iteration/go.mod b/learn_go_with_tests/iteration/go.mod new file mode 100644 index 0000000..c1320df --- /dev/null +++ b/learn_go_with_tests/iteration/go.mod @@ -0,0 +1,3 @@ +module iteration + +go 1.21.0 diff --git a/learn_go_with_tests/iteration/repeat.go b/learn_go_with_tests/iteration/repeat.go new file mode 100644 index 0000000..365334a --- /dev/null +++ b/learn_go_with_tests/iteration/repeat.go @@ -0,0 +1,12 @@ +package iteration + +func Repeat(charaters string, count int) string { + var repeated string + + for i := 0; i < count; i++ { + repeated += charaters + } + + return repeated + +} diff --git a/learn_go_with_tests/iteration/repeat_test.go b/learn_go_with_tests/iteration/repeat_test.go new file mode 100644 index 0000000..e8efbd6 --- /dev/null +++ b/learn_go_with_tests/iteration/repeat_test.go @@ -0,0 +1,41 @@ +package iteration + +import ( + "fmt" + "testing" +) + +func TestRepeat(t *testing.T) { + + t.Run("repeat simple letters", func(t *testing.T) { + repeated := Repeat("a", 6) + expected := "aaaaaa" + + if repeated != expected { + t.Errorf("expected %q but got %q", expected, repeated) + } + }) + + t.Run("repeat words letters", func(t *testing.T) { + repeated := Repeat("dog", 5) + expected := "dogdogdogdogdog" + + if repeated != expected { + t.Errorf("expected %q but got %q", expected, repeated) + } + }) +} + +// This test demonstrates benchmark testing https://pkg.go.dev/testing#hdr-Benchmarks + +func BenchmarkRepeat(b *testing.B) { + for i := 0; i < b.N; i++ { + Repeat("a", 4) + } +} + +func ExampleRepeat() { + repeated := Repeat("da", 5) + fmt.Println(repeated) + // Output: dadadadada +}