Created
December 24, 2018 14:00
-
-
Save acestudiooleg/acb75195471879bb5d62723d41d23425 to your computer and use it in GitHub Desktop.
Redux reducers converter from arrays to function with conditions
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
| const convertReducers = (reducersObject) => { | |
| const newReducers = {}; | |
| console.log(reducersObject); | |
| Object.keys(reducersObject).forEach((reducerName) => { | |
| const { defaultState, reducers } = reducersObject[reducerName]; | |
| newReducers[reducerName] = (state, action) => { | |
| if (/^@/.test(action.type)) { | |
| return state || defaultState || {}; | |
| } | |
| let i = 0; | |
| const len = (reducers || []).length; | |
| for (i; i < len; i += 1) { | |
| const [TYPE, handler] = reducers[i]; | |
| if (action.type === TYPE) { | |
| if (!(handler instanceof Function)) { | |
| console.error(`Reducer function not found for type ${TYPE}`); | |
| return state || defaultState || {}; | |
| } | |
| return Object.assign({}, state, handler(state, action)); | |
| } | |
| } | |
| return state || defaultState || {}; | |
| }; | |
| }); | |
| return newReducers; | |
| }; | |
| const convertedReducers = convertReducers({ | |
| [comDashAppsList.name]: comDashAppsList.default | |
| }); | |
| export default combineReducers(convertedReducers); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment