when expression
Kotlinのwhen式を再現しようとしたものです。
インストール
$ npm install --save when-expression
使い方
when (boolean or number or string) ({ 条件 })
のようにして使います。
等しいプロパティ名(文字列として比較したもの)の値を返します。
該当するプロパティがない場合は、elseの値を返します。elseの定義は必須です。
const color = 'red' const result = red: 1 blue: 2 yellow: 3 else: 9 // 1
when ({ 条件 })
とするとtrueプロパティの値を返します。
const num = 42 const result = // even
使用例
switch文の代替として使えます。
プロパティを関数にすると、その関数を実行した結果を返します。
const str = 'bar' const result = { return 1 } { return 42 } else: 0 console // 42
ReduxのReducerだったらこう書けます。
const initialState = /* ... */ const FOO = 'BAR' { return { /* ... */ } { /* ... */ } { /* ... */ } { /* ... */ } else: state }