dispatcher
Pattern matching for JavaScript.
Library can be used to implement functions supporting range of different dispatchers, in a declarative manner avoiding mess of conditional blocks & manual argument validations. While primarily this aims to improve code readability and maintainability, in some cases this can be useful to optimize specific, hot code paths.
Examples
var dispatcher = dispatcher { if typeofvalue !== 'number' throw Error'Not a number' return value} var sum = // => 0 // => 1 // => 5 // => 25 // TypeError -> Unsupported dispatcher // Define guards { if typeofvalue !== 'string' throw Error'Not a string' return value} { if typeofvalue !== 'function' throw Error'Not a function' return value} { if !Array throw Error'Not an array' return value} { if !value || typeofvalue !== 'object' throw 'Not an object' return value} var map = // => 'HELLO WORLD' // => [ 2, 4, 6 ] // => { '@foo': '1!', '@bar': 'baz!' } // => 7 // TypeError -> Unsupported dispatcher
Install
npm install dispatcher