rust-match

    0.1.7 • Public • Published

    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}!`)
    })
     

    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
      ])
    }

    Install

    npm i rust-match

    DownloadsWeekly Downloads

    4

    Version

    0.1.7

    License

    ISC

    Last publish

    Collaborators

    • avatar