Skip to content

Instantly share code, notes, and snippets.

@thwarted
Last active June 19, 2024 02:00
Show Gist options
  • Save thwarted/a6e5e7ca5ce552311a7d5ece13d298ac to your computer and use it in GitHub Desktop.
Save thwarted/a6e5e7ca5ce552311a7d5ece13d298ac to your computer and use it in GitHub Desktop.
package main
// A simple go iterator implementation.
// Someone could use generics to make this more, well, generic. And
// maybe define a Next() function on a channel receiver to abstract
// away needing the channel <- operator to get the next item and
// and handle the iterator ending cleanly. This uses range which
// already knows how to handle streaming values from channels.
//
// github user: thwarted
import (
"fmt"
)
// upto returns an iterator that emits integers up to the given max
func upto(max int) chan int {
c := make(chan int)
yield := func(i int) { c <- i }
go func() {
for i := range max {
yield(i)
}
close(c)
}()
return c
}
// powersOf2 returns an iterator that emits the powers of 2 up to max
func powersOf2(max uint) chan uint {
c := make(chan uint)
yield := func(i uint) { c <- i }
go func() {
var cur uint = 1
for cur < max {
yield(cur)
cur *= 2
}
close(c)
}()
return c
}
func main() {
myiterator := upto(10)
for i := range myiterator {
fmt.Println("upto emitted ", i)
}
fmt.Println()
for i := range powersOf2(3000) {
fmt.Println("powersOf2 emitted ", i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment