when()
Function in Authoring
Dispatch a value on a condition, returning the value instead of mutating a var.
import { when } from 'typeshade'
The signature, the description and the examples come from the compiler's own source at commit 26de7be8.
Syntax
function when<K extends string>( cond: ReadonlyNode<'bool'>, thenVal: () => ReadonlyNode<K>, elseVal: () => ReadonlyNode<K>,): Node<K>;function when<K extends string>( arms: ReadonlyArray<readonly [ReadonlyNode<'bool'>, () => ReadonlyNode<K>]>, elseVal: () => ReadonlyNode<K>,): Node<K>;Parameters
condReadonlyNode<'bool'>the test, for the two-arm shape.
thenVal() => ReadonlyNode<K>the value when
condholds.elseVal() => ReadonlyNode<K>the value when no condition holds.
armscondition and value pairs, for the N-arm shape, evaluated in order.
Return value
Node<K>
a node reading the chosen value.
Description
Two shapes
are accepted: when(cond, () => a, () => b) for two arms, and
when([[c0, () => e0], [c1, () => e1]], () => eN) for N arms, where the first true
condition wins.
Each arm returns its value; when materialises the var and the if/elif/else chain
internally, so the emit is identical to the hand-written var v; if (c) v = … form. The
arms take values only, with no var name and no type token: the result type comes from the
arms.
Choosing between the three dispatch surfaces is a question about the subject. when is for
condition and range dispatch, where each arm tests something different and there is no
single subject: a threshold ladder, a pair of unrelated flags. Switch and
matchExpr are for dispatch on one integer scrutinee, the value that decides which arm
runs; matchEnum is the same with an exhaustiveness check. select is the eager
two-way form, which evaluates both arms.
ifExpr and condExpr are deprecated aliases of the two-arm and N-arm shapes. They
forward here unchanged.
Examples
Example
import { when, vec2 } from 'typeshade'
const dir = when( segLen.lt(1e-6), () => vec2(1, 0), () => segVec.div(segLen),)
const band = when( [ [level.lt(4), () => coarse], [level.lt(9), () => medium], ], () => fine,)In the guide
See also
Source
src/core/ir/builder.ts, line 2012, at commit 26de7be8