Rook
РусскийRU

Iterators

An iterator is a function whose one parameter is yield, as in Go 1.23: func(yield func(number) bool). It calls yield(v) for each value, and for v in seq goes over them. When the loop stops, the iterator stops at its yield too, as if it had given false, and its defer runs. A yield of two values gives a key and a value: for place, fruit in numbered(fruits). The board can use the same pattern to display or process tasks one at a time; lazy iteration is useful when producing results without first building another collection.

// An iterator is a function with a yield parameter, as in Go 1.23; for goes over it
func fibonacci() func(yield func(number) bool) {
    return func(yield func(number) bool) {
        let a, b = 0, 1
        for {
            // false: the loop over it has stopped, so the iterator ends too
            if !yield(a) {
                return
            }
            a, b = b, a + b
        }
    }
}

for n in fibonacci() {
    if n > 50 {
        break
    }
    console.log(n)
}

// A yield of two values gives a key and a value
func numbered(words string[]) func(yield func(number, string) bool) {
    return func(yield func(number, string) bool) {
        for i, word in words {
            if !yield(i + 1, word) {
                return
            }
        }
    }
}

for place, fruit in numbered(["guava", "papaya", "lychee"]) {
    console.log(place, fruit)
}

// It compiles to a JS generator: called, it gives a lazy JS iterator
const evens = fibonacci()().filter(n => n % 2 == 0).take(5).toArray()
console.log("even:", evens.join(", "))

An iterator compiles to a JS generator, and yield(v) to yield v. So it is a lazy JS iterator too: seq() gives one, with filter, map and take, and JS code goes over it with for...of. For the same reason an iterator calls yield only in its own body, not in a function inside it, and it is not async.