Pipeline Builder
A text-processing pipeline built from composable closures (trim, lowercase, replace, truncate) combined with a Fibonacci iterator using the func() (T, bool) pattern.
package main
import (
"fmt"
"strings"
)
// Pipeline type: a function that transforms a string
type Transform func(string) string
func trimSpaces() Transform {
return strings.TrimSpace
}
func toLower() Transform {
return strings.ToLower
}
func replaceAll(old, new string) Transform {
return func(s string) string {
return strings.ReplaceAll(s, old, new)
}
}
func truncate(maxLen int) Transform {
return func(s string) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen] + "..."
}
}
func pipeline(transforms ...Transform) Transform {
return func(s string) string {
for _, t := range transforms {
s = t(s)
}
return s
}
}
// Iterator pattern: func() (value, hasMore)
func fibonacci() func() (int, bool) {
a, b := 0, 1
count := 0
return func() (int, bool) {
if count >= 20 {
return 0, false
}
count++
result := a
a, b = b, a+b
return result, true
}
}
func rangeIter(start, end, step int) func() (int, bool) {
current := start
return func() (int, bool) {
if current >= end {
return 0, false
}
val := current
current += step
return val, true
}
}
func main() {
// Build a text processing pipeline
slugify := pipeline(
trimSpaces(),
toLower(),
replaceAll(" ", "-"),
replaceAll("&", "and"),
truncate(30),
)
inputs := []string{
" Hello World ",
" Go Programming & Design ",
" Concurrency Patterns In Modern Software Development ",
}
fmt.Println("=== Text Pipeline (slugify) ===")
for _, input := range inputs {
fmt.Printf(" %q\n -> %q\n\n", input, slugify(input))
}
// Fibonacci iterator
fmt.Println("=== Fibonacci Iterator ===")
fib := fibonacci()
fmt.Print(" ")
for {
val, ok := fib()
if !ok {
break
}
fmt.Printf("%d ", val)
}
fmt.Println()
// Range iterator
fmt.Println("\n=== Range Iterator (0 to 50, step 7) ===")
fmt.Print(" ")
next := rangeIter(0, 50, 7)
for {
val, ok := next()
if !ok {
break
}
fmt.Printf("%d ", val)
}
fmt.Println()
}