Created
January 2, 2018 23:21
-
-
Save busypeoples/a05326659b7ad29b68f82e4431d9efab to your computer and use it in GitHub Desktop.
Simplified Redux Reducers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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