Skip to content

Instantly share code, notes, and snippets.

@thwarted
Last active June 19, 2024 02:00
Show Gist options
  • Select an option

  • Save thwarted/a6e5e7ca5ce552311a7d5ece13d298ac to your computer and use it in GitHub Desktop.

Select an option

Save thwarted/a6e5e7ca5ce552311a7d5ece13d298ac to your computer and use it in GitHub Desktop.

Revisions

  1. thwarted revised this gist Jun 19, 2024. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions go-iterator.go
    Original file line number Diff line number Diff line change
    @@ -15,11 +15,11 @@ import (

    // upto returns an iterator that emits integers up to the given max
    func upto(max int) chan int {
    yield := func(x chan int, i int) { x <- i }
    c := make(chan int)
    yield := func(i int) { c <- i }
    go func() {
    for i := range max {
    yield(c, i)
    yield(i)
    }
    close(c)
    }()
    @@ -28,12 +28,12 @@ func upto(max int) chan int {

    // powersOf2 returns an iterator that emits the powers of 2 up to max
    func powersOf2(max uint) chan uint {
    yield := func(x chan uint, i uint) { x <- i }
    c := make(chan uint)
    yield := func(i uint) { c <- i }
    go func() {
    var cur uint = 1
    for cur < max {
    yield(c, cur)
    yield(cur)
    cur *= 2
    }
    close(c)
  2. thwarted created this gist Jun 19, 2024.
    55 changes: 55 additions & 0 deletions go-iterator.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    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 {
    yield := func(x chan int, i int) { x <- i }
    c := make(chan int)
    go func() {
    for i := range max {
    yield(c, i)
    }
    close(c)
    }()
    return c
    }

    // powersOf2 returns an iterator that emits the powers of 2 up to max
    func powersOf2(max uint) chan uint {
    yield := func(x chan uint, i uint) { x <- i }
    c := make(chan uint)
    go func() {
    var cur uint = 1
    for cur < max {
    yield(c, 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)
    }
    }