0.0.8 • Published 8 years ago
switch-js v0.0.8
switch-js
Install
npm i switch-jsExample
const switcher = require('switch-js');
const valueToTest = 'foo';
switcher(valueToTest)
.case('foo', () => console.log('foo!'))
.case('bar', () => console.log('bar!'))
.default(() => console.log('no match found in given cases!'))
.always(() => console.log('this is cool!'));
// result:
// foo!
// this is cool!Check for multiple cases:
switcher(valueToTest)
.cases(['foo', 'bar'], () => console.log('foo or bar!'))
.default(() => console.log('no match found in given cases!'));
// result: foo or bar!Check if value is matched by a function:
switcher(valueToTest)
.caseWhen(value => typeof value === 'string', () => console.log('a string!'))
.caseWhen(value => typeof value === 'number', () => console.log('a number!'))
.default(() => console.log('other datatypes!'));
// result: a string!Use to to set value:
const valueInUppercase = switcher(valueToTest)
.case('foo').to('FOO!')
.case('bar').to('BAR!')
.value('NO MATCH FOUND!');
// result: FOO!
// .value('NO MATCH FOUND!')
// has the same effect as
// .default().to('NO MATCH FOUND!').value()Use mapTo to set the value by a function:
const valueInUppercase = switcher(valueToTest)
.cases(['foo', 'bar']).mapTo(value => value.toUpperCase())
.default().mapTo(value => value.toUpperCase() + ' IS NOT A MATCH!')
.value();
// result: 'FOO'API
switch(value)
start a switch chain
valueValue to check
case(caseValue[, matchedCallback][, notMatchedCallback])
The case method you know
caseValuematchedCallbackFunction, optional. Invoked ifcaseValueequals deeply tovaluenotMatchedCallbackFunction, optional. Invoked otherwise
cases(caseValues[, matchedCallback][, notMatchedCallback])
Check for multiple case values
caseValuesArray ofcaseValuematchedCallbackFunction, optional. Invoked ifcaseValuesincludesvaluenotMatchedCallbackFunction, optional. Invoked otherwise
caseWhen(matcher[, matchedCallback][, notMatchedCallback])
Check by a function
matcherA match function used to check ifvalueis a matchmatchedCallbackFunction, optional. Invoked ifmatcher(value)returns a truthy valuenotMatchedCallbackFunction, optional. Invoked otherwise
default([noMatchFoundCallback, matchFoundCallback])
The default method you know
noMatchFoundCallbackFunction, optional. Invoked if no match is foundmatchFoundCallbackFunction, optional. Invoked otherwise
always(callback)
Invoked anyway
callbackFunction
to(valueToReturn)
Set a new value to return by value() if previous case is a match or it follows default()
valueToReturn
mapTo(mapper)
Similiar to to() but set value by a mapper function
mapperFunction | String. If a string is passed, it will take as a path and invoke_.get(valueToTest, path)from lodash
value(defaultValue)
Return the value
defaultValueDefault value will return if no match is found