Rook
РусскийRU
// `go` runs a function on another thread, with copies of its arguments and its result.
func square(n number) number {
return n * n
}
const result = await go square(7)
const values = [1, 2, 3, 4]
go for i, value in values {
values[i] = value * value
}
console.log("result:", result)
console.log("parallel:", values.join(", "))
move 12 of 18 · $$goroutine0 3

$$goroutine0 3 sends […] back to main as its result.

Goroutines

JavaScript runs a program in one thread: a long computation stops everything else, and a worker takes a file of its own and messages written by hand. In Rook it is one word, as in Go, and the compiler checks what goes to the other thread.

go f(x) calls a function as a goroutine, in another thread, and gives a Promise of the result. Goroutines run at once on different processors: the threads are a pool of workers, Web Workers in the browser and worker threads in Node, up to one per processor. A goroutine shares no memory with the program: it gets copies of the arguments and sends back a copy of the result, so they are data, and the function cannot use the let variables of the module. The compiler checks both.

// go runs a function as a goroutine, in another thread; it gets copies of the arguments
func isPrime(n number) bool {
    if n < 2 {
        return false
    }

    for let d = 2; d * d <= n; d++ {
        if n % d == 0 {
            return false
        }
    }
    return true
}

// What countPrimes uses, isPrime, goes to the other thread with it
func countPrimes(from, to number) number {
    let count = 0
    for let n = from; n < to; n++ {
        if isPrime(n) {
            count++
        }
    }
    return count
}

const PART = 1_000_000

let started = Date.now()
console.log("one thread:", countPrimes(0, 10 * PART), `${Date.now() - started} ms`)

// go gives a Promise of the result: the ten parts are counted at once
started = Date.now()
const parts = await Promise.all(Array(10).fill(0).map((_, i) => go countPrimes(i * PART, (i + 1) * PART)))
console.log("ten goroutines:", parts.reduce((a, b) => a + b, 0), `${Date.now() - started} ms`)

The board uses goroutines for background task work that keeps a processor busy. A worker receives task data and returns its result; channels carry commands and results between the worker and the rest of the app.

go func(n number) { ... }(i) runs a function literal as a goroutine: the local names it uses are copied to it, like its arguments. transfer(x) moves an ArrayBuffer or a typed array to the goroutine instead of copying it, and leaves it empty here. go is for work that keeps a processor busy; to wait for a timer or the network, call an async function without await: it runs at once in the same thread.

// go func(...) { ... }(...) runs a function literal as a goroutine;
// the local names it uses are copied to it, like its arguments
async func sumInParts(numbers number[], parts number) number {
    const size = Math.ceil(numbers.length / parts)
    const sums = chan<number>(parts)
    for let i = 0; i < parts; i++ {
        go async func(from number) {
            let sum = 0
            for n in numbers.slice(from, from + size) {
                sum += n
            }
            sums <- sum
        }(i * size)
    }

    let total = 0
    for let i = 0; i < parts; i++ {
        total += <-sums
    }
    close(sums) // every part has sent its sum
    return total
}

const numbers number[] = []
for let i = 1; i <= 100_000; i++ {
    numbers.push(i)
}
console.log("sum:", await sumInParts(numbers, 4))

// transfer() moves a buffer to the goroutine instead of copying it
func average(values Float64Array) number {
    return values.reduce((a, b) => a + b, 0) / values.length
}

const values = new Float64Array(1_000_000).fill(2)
const pending = go average(transfer(values))
console.log("left here:", values.length)
console.log("average:", await pending)

go for i, v in items { ... } is a parallel loop: the array is split into parts, several per processor, each part runs as a goroutine in the first worker that is free, and the loop waits for all of them. A worker gets only its part, so the body writes only its own element, items[i], and reads other elements from another array; the other names it uses are copied to it, as to a function literal.

// go for splits an array among the processors: each part runs as a
// goroutine, and the loop waits for all of them
const pixels = new Uint8ClampedArray(1_000_000)
for i, _ in pixels {
    pixels[i] = i % 256
}

const contrast = 1.5
go for i, v in pixels {
    pixels[i] = (v - 128) * contrast + 128
}
console.log("contrast:", pixels[100], pixels[200])

// the body writes only its own element; neighbours come from another array
async func smooth(values number[]) number[] {
    const out = values.map(_ => 0)
    go for i, _ in out {
        const left = values[Math.max(i - 1, 0)]
        const right = values[Math.min(i + 1, values.length - 1)]
        out[i] = (left + values[i] + right) / 3
    }
    return out
}

console.log("smooth:", await smooth([3, 6, 9, 12, 15]))

A copy keeps the data of a value but not its class, so an instance of a class cannot go to a goroutine, unless the class is a data class: its fields are data, and its instances go to goroutines and back, and through channels, with their class, so the other thread calls their methods. A subclass of one is marked too: data class Admin extends User.

// A copy that goes to another thread has the data of a value but not its class; a data class
// goes with its class, so the goroutine can call its methods
data class Order {
    items number[]

    constructor(items number[]) {
        this.items = items
    }

    total() number {
        return this.items.reduce((sum, price) => sum + price, 0)
    }
}

func biggest(orders Order[]) Order {
    let best = orders[0]
    for order in orders {
        if order.total() > best.total() {
            best = order
        }
    }
    return best
}

const orders = [new Order([3, 4]), new Order([10, 2, 1]), new Order([7])]
const best = await go biggest(orders)
console.log(best instanceof Order, best.total())