Skip to content

Instantly share code, notes, and snippets.

@mtmr0x
Created December 3, 2017 17:54
Show Gist options
  • Select an option

  • Save mtmr0x/9a6e05069f0b27fce2be1d54b9742b38 to your computer and use it in GitHub Desktop.

Select an option

Save mtmr0x/9a6e05069f0b27fce2be1d54b9742b38 to your computer and use it in GitHub Desktop.
const ifFunction = f => {
if (typeof f === 'function')
return f();
return f;
};
const switchcaseF = cases => defaultCase => key => {
if (key in cases)
return cases[key];
return defaultCase;
}
const switchcase = (cases = {}) => (defaultCase = {}) => (key = '') =>
ifFunction(switchcaseF(cases)(defaultCase)(key));
export default switchcase;

switchcase

switchcase is an internal Redux utility built for avoiding use the the switch statement, because "it's not immutable, it can't be composed with other functions, and it's a little side effecty". Concepts for this use is located in https://hackernoon.com/rethinking-javascript-eliminate-the-switch-statement-for-better-code-5c81c044716d.

switchcase(cases)(defaultCase)(key)

switchcase is a curried function which executes its curried callbacks in three levels, and its arguments are:

cases: an object for receiving the possible cases to be matched following this model:

{
  TRIGGER_EXAMPLE: action.example,
  USER_STATUS: action.status,
}

defaultCase: the defaultCase is the state itself. From a reducer, its execution is:

export default function exampleReducer(state = {}, action) {
  return switchcase({
    TRIGGER_EXAMPLE: action.example
  })(state)(action.type);
}

key: used for receiving the action type in the reducer as showed in defaultCase argument example. It is used to match the case and return the value from matched object key in cases.

import switchcase from './index';
describe('switchcase utility', () => {
it('pass single case and returns proper value', () => {
const s = switchcase(
{ TRIGGER_EXAMPLE: { example: true } }
)({})('TRIGGER_EXAMPLE');
expect(JSON.stringify(s)).toBe(JSON.stringify({ example: true }));
});
it('pass multiple cases and returns proper value', () => {
const s = switchcase(
{
TRIGGER_EXAMPLE: { example: true },
TRIGGER_EXAMPLE_FALSE: { example: false }
}
)({})('TRIGGER_EXAMPLE');
expect(JSON.stringify(s)).toBe(JSON.stringify({ example: true }));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment