hash-switch
v2.2.1
Published
Switch pattern based on object hash
Downloads
13
Readme
hash-switch
This lib is made to give you the same functionality as a switch
statement but with a more natural API.
Compare:
switch(expression) {
case 'one':
return 'ONE';
break;
case 'two':
return 'TWO';
break;
default:
return 'DEFAULT';
break;
}
To:
hs({
'one':function(){ return 'ONE' },
'two':function(){ return 'TWO' }
},
function() { return 'DEFAULT' })
For me the second example is a much more familiar syntax and meshes with my other JavaScript more naturally.
Install
npm i hash-switch --save
Usage
var hs = require('hash-switch')({
'one': function() {return 'ONE'},
'two': function() {return 'TWO'},
/* Extra arguments will be passed to the callback function */
'three': function(four) {return 'THREE' + ' ' + four}
},
function(){return 'DEFAULT'}
)
hs('one') //ONE
hs('two') //TWO
/* You can pass an extra argument to the callback function like so */
hs('three', 'FOUR') //THREE FOUR
hs('nope') //DEFAULT