Created
January 17, 2019 15:02
-
-
Save beautyfree/3edf28e0584eadbd79318c0ee8ed86ba to your computer and use it in GitHub Desktop.
This file contains 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
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