Skip to content

Instantly share code, notes, and snippets.

@beautyfree
Created January 17, 2019 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beautyfree/3edf28e0584eadbd79318c0ee8ed86ba to your computer and use it in GitHub Desktop.
Save beautyfree/3edf28e0584eadbd79318c0ee8ed86ba to your computer and use it in GitHub Desktop.
import { path, mergeAll } from 'ramda';
function entitiesReducer(entitiesName, reducer) {
return (state, action) => {
const entities = path(['payload', 'entities', entitiesName], action);
let newState;
if (entities) {
if (state) {
newState = mergeAll([{}, state, entities]);
} else {
newState = entities;
}
} else {
newState = state;
}
return reducer(newState, action);
};
}
export default function combineEntitiesReducers(reducers) {
const wrappedReducers = [];
Object.keys(reducers).forEach(fieldName => {
wrappedReducers.push({
fieldName,
reducer: entitiesReducer(fieldName, reducers[fieldName]),
});
});
return (state = {}, action) => {
const newState = {};
let someUpdated = false;
wrappedReducers.forEach(({ fieldName, reducer }) => {
const prevSubState = state[fieldName];
const newSubState = reducer(prevSubState, action);
newState[fieldName] = newSubState;
if (prevSubState !== newSubState) {
someUpdated = true;
}
});
if (someUpdated) {
return newState;
}
return state;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment