0.0.2 • Published 6 years ago

when-expression v0.0.2

Weekly downloads
2
License
MIT
Repository
-
Last release
6 years ago

when expression

Kotlinのwhen式を再現しようとしたものです。

インストール

$ npm install --save when-expression

使い方

when (boolean or number or string) ({ 条件 })のようにして使います。
等しいプロパティ名(文字列として比較したもの)の値を返します。
該当するプロパティがない場合は、elseの値を返します。elseの定義は必須です。

import when from 'when-expression'

const color = 'red'

const result = when (color) ({
  red: 1,
  blue: 2,
  yellow: 3,
  else: 9
}) // 1

when ({ 条件 })とするとtrueプロパティの値を返します。

const num = 42

const result = when ({
  [num % 2 === 0]: 'even',
  else: 'odd'
}) // even

使用例

switch文の代替として使えます。
プロパティを関数にすると、その関数を実行した結果を返します。

const str = 'bar'

const result = when (str) ({
  foo() { 
    return 1 
  },
  bar() {
    return 42
  },
  else: 0
})

console.log(result) // 42

ReduxのReducerだったらこう書けます。

const initialState = { /* ... */ }
const FOO = 'BAR'

export default function sample(state = initialState, action) {
  return when (action.type) ({
    ADD() { /* ... */ },
    UPDATE() { /* ... */ },
    CLEAR() { /* ... */ },
    [FOO]() { /* ... */ },
    else: state
  })
}