@zedux/core
Version:
A high-level, declarative, composable form of Redux
39 lines (37 loc) • 1.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReducer = void 0;
const actions_1 = require("../utils/actions");
/**
Creates a new ReducerBuilder.
A ReducerBuilder is just a reducer with a special `.reducer()` method for
easily mapping action types to sub-reducers that handle them.
*/
const createReducer = (initialState) => {
const actionToReducersMap = {};
const reducer = ((state = initialState, action) => {
const reducers = actionToReducersMap[action.type] || [];
return runReducers(reducers, state, action);
});
reducer.reduce = (reactable, subReducer) => {
const method = 'ReducerBuilder.reduce()';
const actionTypes = Array.isArray(reactable)
? (0, actions_1.extractActionTypes)(reactable, method)
: [(0, actions_1.extractActionType)(reactable, method)];
mapActionTypesToReducer(actionToReducersMap, actionTypes, subReducer);
return reducer;
};
return reducer;
};
exports.createReducer = createReducer;
const mapActionTypesToReducer = (map, actionTypes, consumer) => {
actionTypes.forEach(actionType => {
if (!map[actionType]) {
map[actionType] = [];
}
map[actionType].push(consumer);
});
};
const runReducers = (reducers, state, action) => {
return reducers.reduce((accumulatedState, reducer) => reducer(accumulatedState, action.payload, action), state);
};