Skip to content

garbles/match

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 npmcdn:

<script src="https://npmcdn.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
  ])
}

About

a port of Rust's match in JS

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%