sac.js 1.1 KB

12345678910111213141516171819202122232425262728
  1. import {atPath} from 'atpath';
  2. export const subReducer = (key, reducer, ...otherKeys) => {
  3. const atKey = atPath(key),
  4. otherParts = otherKeys.map(atPath);
  5. return (state, action) => {
  6. const newSubState = reducer(atKey.get(state), action, ...otherParts.map(eachSelector => eachSelector.get(state)));
  7. if (typeof newSubState === "undefined") {
  8. throw new Error(`The '${key}' reducer must not return undefined.`);
  9. }
  10. return atKey.put(newSubState)(state);
  11. };
  12. };
  13. export const composeReducers = (...reducers) => (state, action) =>
  14. reducers.reduce((x, r) => r(x, action), state);
  15. export const subMiddleware = (keyOrSelectorFn, middleware) => {
  16. const selector = typeof keyOrSelectorFn === "function" ? keyOrSelectorFn : atPath(keyOrSelectorFn).get;
  17. return (store, ...rest) => {
  18. const {getState} = store;
  19. return middleware({...store, getState: () => selector(getState())}, ...rest);
  20. };
  21. };
  22. export const subEffex = (keyOrSelectorFn, effects) =>
  23. effects.map(each => ({...each, effect: subMiddleware(keyOrSelectorFn, each.effect)}));