Created
March 22, 2018 11:19
-
-
Save SRatna/a4bcea0293d527b2bea531874191f741 to your computer and use it in GitHub Desktop.
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
| /** | |
| * Create valid redux reducer with action types as object keys and values as | |
| * functions, instead of using Switch Statement | |
| * | |
| * Use it like this: | |
| * | |
| * `createReducer({ | |
| * // optional if you set a initial state as the second argument | |
| * initialState: {}, | |
| * | |
| * SOME_ACTION_TYPE: (state, action) => { | |
| * //...do something | |
| * return state | |
| * } | |
| * }, {// some initial state }) // optional if you set it above | |
| * ` | |
| * | |
| * @param {Object} reducerMap Actions handlers and/or initial state | |
| * @param {*} [initialState=reducerMap.initialState] | |
| * @return {function} | |
| */ | |
| export default (reducerMap, initialState) => { | |
| if (typeof reducerMap.initialState === 'undefined' && typeof initialState === 'undefined') { | |
| throw new Error('initialState is undefined') | |
| } | |
| if (typeof reducerMap.initialState !== 'undefined' && typeof initialState === 'undefined') { | |
| initialState = reducerMap.initialState | |
| } | |
| return (state = initialState, action) => { | |
| const reducer = action && reducerMap[action.type] | |
| return reducer ? reducer(state, action) : state | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment