Rook
РусскийRU

Conditions and loops

Conditions and loops are as in Go: no parentheses around the condition and always braces. There is one loop, for: over an array, with a condition, over a range of numbers, for i in 0..n, without n, and the classic one with three parts. It also goes over a Map, by keys and values, over a Set and a typed array, which is indexed as an array is. switch has no break: each case ends by itself. For the board, its own rules can allow done to change fromfalse to true only when the task is eligible; Rook provides the branching tools, not a built-in task state machine.

const fruits = ["guava", "papaya", "lychee"]

// for x in xs gives values, for i, x in xs gives indexes and values
for i, fruit in fruits {
    console.log(i + 1, fruit)
}

// A Map gives keys and values, as a map in Go; one variable gets the values
const prices = new Map()
prices.set("guava", 3).set("lychee", 7)
for name, price in prices {
    console.log(name, price)
}

// There is one loop, for: it is also while, a range and the loop with three parts
let left = 3
for left > 0 {
    left--
}
for i in 0..2 {
    console.log("step", i)
}
for let i = 10; i > 0; i -= 5 {
    console.log("down", i)
}

// switch has no break; without an expression it works like a chain of ifs
func grade(score number) string {
    switch {
    case score >= 90:
        return "excellent"
    case score >= 60:
        return "pass"
    default:
        return "fail"
    }
}

console.log(grade(95), grade(70), grade(10))

As in Go, if and switch can start with an initializer: if const n, err = parse(text); err != null. Its variables are seen in every branch and not after the statement. A label before a loop lets break and continue in a nested loop leave the outer one.

func parse(text string) (number, ?error) {
    const n = parseInt(text)
    if isNaN(n) {
        return 0, error(`not a number: ${text}`)
    }
    return n, null
}

// The variables of the initializer are seen in every branch, and not after the if
for text in ["12", "guava"] {
    if const n, err = parse(text); err != null {
        console.log(err.message)
    } else {
        console.log(n * 2)
    }
}

// A label lets break and continue leave the loop around the one they are in
const grid = [[1, 2, 3], [4, -1, 6], [7, 8, 9]]
outer: for row in grid {
    for v in row {
        if v < 0 {
            console.log("a negative number: stop")
            break outer
        }
        console.log(v)
    }
}