All Projects → zackify → Match

zackify / Match

a port of Rust's match in JS

Programming Languages

javascript
184084 projects - #8 most used programming language

Build Status

Match

A basic port of Rust's match function.

Install

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:

<script src="https://unpkg.com/rust-match/umd/match.min.js"></script>

Examples

Play around on JSFiddle

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 than a switch statement though.

Exhaustive Checking

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!

export default (state = Immutable.Map, action) => {
  return match(action.type, [
    authenticate => state.merge(action),
    setToken => state.set('token', 'test'),
    _ => state
  ])
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].