Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Created January 2, 2018 23:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save busypeoples/a05326659b7ad29b68f82e4431d9efab to your computer and use it in GitHub Desktop.
Save busypeoples/a05326659b7ad29b68f82e4431d9efab to your computer and use it in GitHub Desktop.
Simplified Redux Reducers
import Maybe from 'folktale/maybe';
const Inc = 'Inc';
const Dec = 'Dec';
const IncBy = 'IncBy';
const IncFn = state => state + 1;
const DecFn = state => state - 1;
const IncByFn = (state, action) => state + action.incBy;
const Actions = { [Inc]: IncFn, [Dec]: DecFn, [IncBy]: IncByFn };
const CounterReducer = (state = 0, action) =>
Maybe.fromNullable(Actions[action.type]).matchWith({
Just: ({ value }) => value(state, action),
Nothing: () => state
});
CounterReducer(4, { type: Inc }); //=> 5
CounterReducer(undefined, { type: Inc }); //=> 1
CounterReducer(4, { type: Dec }); //=> 3
CounterReducer(undefined, { type: Dec }); // => -1
CounterReducer(4, { type: IncBy, incBy: 5 }); // => 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment