UNPKG

@zedux/core

Version:

A high-level, declarative, composable form of Redux

35 lines (33 loc) 1.32 kB
import { extractActionType, extractActionTypes } from '../utils/actions.js'; /** 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. */ export 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) ? extractActionTypes(reactable, method) : [extractActionType(reactable, method)]; mapActionTypesToReducer(actionToReducersMap, actionTypes, subReducer); return reducer; }; return reducer; }; 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); };