Skip to content

Instantly share code, notes, and snippets.

@acestudiooleg
Created December 24, 2018 14:00
Show Gist options
  • Select an option

  • Save acestudiooleg/acb75195471879bb5d62723d41d23425 to your computer and use it in GitHub Desktop.

Select an option

Save acestudiooleg/acb75195471879bb5d62723d41d23425 to your computer and use it in GitHub Desktop.
Redux reducers converter from arrays to function with conditions
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