https://github.com/zackify/match
a port of Rust's match in JS
https://github.com/zackify/match
Last synced: 12 months ago
JSON representation
a port of Rust's match in JS
- Host: GitHub
- URL: https://github.com/zackify/match
- Owner: zackify
- Created: 2016-01-21T02:33:18.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2017-03-28T18:40:44.000Z (almost 9 years ago)
- Last Synced: 2025-02-27T08:54:38.853Z (about 1 year ago)
- Language: JavaScript
- Size: 11.7 KB
- Stars: 77
- Watchers: 4
- Forks: 7
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://circleci.com/gh/zackify/match)
## Match
A basic port of [Rust's match](https://doc.rust-lang.org/book/match.html) function.
## Install
```js
npm install rust-match --save
import match from 'rust-match'
```
You can get the UMD build from `/umd`, or use it in a script tag from unpkg:
```
```
## Examples
#### [Play around on JSFiddle](https://jsfiddle.net/2ct8d7r9/10/)
```js
let message = 'hello'
let response = match(message, [
hello => 'the value is hello',
goodbye => 'hello to you too!',
_ => 'something else'
])
console.log(response) // prints 'the value is hello'
//numbers and spaces are more verbose
let number = '26'
match(number, {
5: () => console.log('the value is hi'),
'test word': () => console.log('the value is test word'),
_: (value) => console.log(`you chose ${value}!`)
})
```
It is [a LOT slower](http://jsperf.com/match-vs-switch/11) than a switch statement though.
## Exhaustive Checking
```js
match('test', [
awesome => console.log('awesome')
])
//throws: error: non-exhaustive patterns: `_` not covered, just like rust!
```
## Usage with Redux
This also turns out to be a nice alternative to using switch statements in redux!
```js
export default (state = Immutable.Map, action) => {
return match(action.type, [
authenticate => state.merge(action),
setToken => state.set('token', 'test'),
_ => state
])
}
```