Skip to content

kristoferjoseph/hash-switch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Switch pattern based on object hash

Resources

Stars

Watchers

Forks

Packages

No packages published