2.1.0 • Published 8 years ago

better-switch v2.1.0

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

Better switch statement

Travis David David Dev npm

The native Javascript switch statement doesn't really fit into the common coding style of Javascript code. Therefore this module aims to handle such use cases in a more intuitive way. This module does not offer the "fall-through" mechanism of a native switch statement.

Usage

npm install -S better-switch

Pass an object as first argument. The default part will be executed in case nothing else matches. If default is not specified and nothing matches it will return undefined.

var betterSwitch = require('better-switch');

var map = {
  foo: function () {
    return 'bar';
  },
  baz: 42,
  default: 'default'
};

var result = betterSwitch('foo', map); // => bar

The associated value can be of any type. If it is a function it will be executed and the result returned. With ES2015 you can make it even clearer:

const baz = 42,
const map = {
  foo: () => 'bar',
  baz,
  default: 'default'
};
const result = betterSwitch('baz', map); // => 42

If you want to return a function you have to wrap it in a function. This is required, because otherwise the function will be executed.

const map = {
  func: function() {
    return function() {
      // do stuff
    }
  }
}
2.1.0

8 years ago

2.0.2

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago