package main import "fmt" // IteratorWrapper struct met generics type IteratorWrapper[T any] struct { iter []T } // Constructor voor IteratorWrapper func From[T any](iterable []T) *IteratorWrapper[T] { return &IteratorWrapper[T]{iter: iterable} } // map functie func (iw *IteratorWrapper[T]) Map(f func(T) T) *IteratorWrapper[T] { result := make([]T, len(iw.iter)) for i, x := range iw.iter { result[i] = f(x) } return From(result) } // filter functie func (iw *IteratorWrapper[T]) Filter(f func(T) bool) *IteratorWrapper[T] { var result []T for _, x := range iw.iter { if f(x) { result = append(result, x) } } return From(result) } // take functie func (iw *IteratorWrapper[T]) Take(n int) *IteratorWrapper[T] { if n > len(iw.iter) { n = len(iw.iter) } return From(iw.iter[:n]) } // toArray functie func (iw *IteratorWrapper[T]) ToArray() []T { return iw.iter } func main() { numbers := []int{1, 2, 3, 4, 5} result := From(numbers). Map(func(x int) int { return x * 2 }). Filter(func(x int) bool { return x > 5 }). Take(2). ToArray() fmt.Println(result) // [6, 8] // Voorbeeld met een ander datatype, zoals strings strings := []string{"apple", "banana", "cherry", "date"} stringResult := From(strings). Filter(func(s string) bool { return len(s) > 5 }). Take(2). ToArray() fmt.Println(stringResult) // ["banana", "cherry"] }
897700cookie-checkGo IteratorWrapper