Split RepeatFive, handle counts, add examples
This commit is contained in:
@@ -2,11 +2,18 @@ package iteration
|
|||||||
|
|
||||||
import "strings"
|
import "strings"
|
||||||
|
|
||||||
const repeatCount = 5
|
const defaultRepeatCount = 5
|
||||||
|
|
||||||
func Repeat(character string) string {
|
func RepeatFive(character string) string {
|
||||||
|
return Repeat(character, defaultRepeatCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Repeat(character string, count int) string {
|
||||||
|
if count == 0 {
|
||||||
|
count = defaultRepeatCount
|
||||||
|
}
|
||||||
var repeated strings.Builder
|
var repeated strings.Builder
|
||||||
for range repeatCount {
|
for range count {
|
||||||
repeated.WriteString(character)
|
repeated.WriteString(character)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,36 @@
|
|||||||
package iteration
|
package iteration
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestRepeat(t *testing.T) {
|
func TestRepeat(t *testing.T) {
|
||||||
got := Repeat("a")
|
t.Run("RepeatFive a", func(t *testing.T) {
|
||||||
want := "aaaaa"
|
got := RepeatFive("a")
|
||||||
assertResult(t, got, want)
|
want := "aaaaa"
|
||||||
|
assertResult(t, got, want)
|
||||||
|
})
|
||||||
|
t.Run("RepeatFive z", func(t *testing.T) {
|
||||||
|
got := RepeatFive("z")
|
||||||
|
want := "zzzzz"
|
||||||
|
assertResult(t, got, want)
|
||||||
|
})
|
||||||
|
t.Run("repeat z, 11 times", func(t *testing.T) {
|
||||||
|
got := Repeat("z", 11)
|
||||||
|
want := "zzzzzzzzzzz"
|
||||||
|
assertResult(t, got, want)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRepeatFive() {
|
||||||
|
fmt.Println(RepeatFive("y"))
|
||||||
|
// Output: yyyyy
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleRepeat() {
|
||||||
|
fmt.Println(Repeat("t", 7))
|
||||||
|
// Output: ttttttt
|
||||||
}
|
}
|
||||||
|
|
||||||
func assertResult(t testing.TB, got, want string) {
|
func assertResult(t testing.TB, got, want string) {
|
||||||
@@ -17,6 +42,6 @@ func assertResult(t testing.TB, got, want string) {
|
|||||||
|
|
||||||
func BenchmarkRepeat(b *testing.B) {
|
func BenchmarkRepeat(b *testing.B) {
|
||||||
for b.Loop() {
|
for b.Loop() {
|
||||||
Repeat("a")
|
RepeatFive("a")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user