when
이 페이지에서

when()

함수, 작성 분류

Dispatch a value on a condition, returning the value instead of mutating a var.

import { when } from 'typeshade'

시그니처, 설명, 예제는 커밋 c66579bf의 컴파일러 소스에서 그대로 가져온 영어 원문입니다.

구문

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>;

매개변수

cond ReadonlyNode<'bool'>

the test, for the two-arm shape.

thenVal () => ReadonlyNode<K>

the value when cond holds.

elseVal () => ReadonlyNode<K>

the value when no condition holds.

arms

condition and value pairs, for the N-arm shape, evaluated in order.

반환값

Node<K>

a node reading the chosen value.

설명

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.

예제

예제

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,
)

관련 가이드

함께 보기

소스

src/core/ir/builder.ts, 2012행, 커밋 c66579bf 기준

이 페이지 편집 문제 보고