# when-expression

> when expression like kotlin's

Latest version **0.0.2** (published 2018-05-01) · MIT license · 0 weekly downloads

## Install

```sh
npm install when-expression
pnpm add when-expression
yarn add when-expression
bun add when-expression
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.2 |
| Published | 2018-05-01 |
| First published | 2018-04-30 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 150.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | tetsugi |
| Maintainers | tetsugi |
| Keywords | switch, switch expression, when, when expression |

## Links

- npm: https://www.npmjs.com/package/when-expression
- npm.io page: https://npm.io/package/when-expression

## Recent versions

- 0.0.2 (latest) — 2018-05-01
- 0.0.1 — 2018-04-30

## README

# when expression

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

## インストール

```sh
$ npm install --save when-expression
```

## 使い方

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

```js
import when from 'when-expression'

const color = 'red'

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

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

```js
const num = 42

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

## 使用例

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

```js
const str = 'bar'

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

console.log(result) // 42
```

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

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

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

---
_Source: https://npm.io/package/when-expression · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
