Skip to content

Instantly share code, notes, and snippets.

@alexengrig
Last active March 5, 2019 11:48
Show Gist options
  • Save alexengrig/89fd5f616031ebb7165b1dc793a22046 to your computer and use it in GitHub Desktop.
Save alexengrig/89fd5f616031ebb7165b1dc793a22046 to your computer and use it in GitHub Desktop.
Function of create a reduce function for Redux store
function createReduce(reducer = {}, initialState) {
return (state = initialState, action) => {
const { type: actionType } = action;
const func = reducer[actionType];
const newState = typeof func === 'function' ? func.call(reducer, state, action) : undefined;
return newState !== undefined ? newState : state;
};
}
// example
const SOME_ACTION = 'SOME_ACTION';
const reducer = { [SOME_ACTION]: (state, { payload }) => payload };
const reduce = createReduce(reducer);
const state = false;
const action = { type: SOME_ACTION, payload: true };
const newState = reduce(state, action);
// => newState is true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment