Rook
РусскийRU

Functions

A function is declared with func. Parameters of the same type can be listed together, and a function can have several results, unpacked into several variables. In the board, ordinary functions can add a task, mark one complete or filter the collection; these are app operations, not special language APIs.

Literals func(x number) number { ... } and arrow functions x => x * 2 compile to JS arrow functions, so this in them is the one outside. Such a function in the initializer of a variable runs after the initializer, so it can use the variable: a recursive literal, or a callback that stops its own timer. If the type of the function depends on its body, as for const f = () => f(), the variable needs a written type.

Parameters at the end may have default values, times = 1, and the last one may take the rest of the arguments in an array, ...prices number[], as in JS. A function before a template, money`${120}`, is its tag: it gets the strings and the values, which are checked against its parameters.

// Several parameters of the same type and several results
func divmod(a, b number) (number, number) {
    return Math.floor(a / b), a % b
}

const q, r = divmod(17, 5)
console.log(`17 = 5 × ${q} + ${r}`)

// A function literal and an arrow function
const square = func(x number) number {
    return x * x
}
const doubled = [1, 2, 3].map(x => x * 2)

// A function in the initializer of a variable runs later, so it can use the variable
const factorial = func(n number) number {
    return n <= 1 ? 1 : n * factorial(n - 1)
}
console.log(square(4), doubled, factorial(5))

// Default values at the end, and the rest of the arguments in an array
func greet(name string = "guest", times = 1) string {
    return `Hi, ${name}! `.repeat(times)
}

func total(label string, ...prices number[]) string {
    return `${label}: ${prices.reduce((sum, p) => sum + p, 0)}`
}
console.log(greet(), greet("Ann", 2), total("cart", 120, 90))

// A tag gets the strings of a template and its values
func money(parts string[], ...values number[]) string {
    return parts.map((part, i) => i < values.length ? `${part}${values[i].toFixed(2)} ₽` : part).join("")
}
console.log(money`Guavas cost ${120} and limes ${90}`)