Commit a50bf888 authored by Robert Knight's avatar Robert Knight

Improve types and identifier names in `createReducer`

parent 4ca56948
...@@ -15,26 +15,31 @@ export function actionTypes(reducers) { ...@@ -15,26 +15,31 @@ export function actionTypes(reducers) {
} }
/** /**
* Given objects which map action names to update functions, this returns a * Create a standard Redux reducer function from a map of action types to reducers.
* reducer function that can be passed to the redux `createStore` function.
* *
* @param {Object} actionToUpdateFn - Object mapping action names to update * @template {object} State
* functions. * @param {Record<string, (s: State, action: any) => Partial<State>>} reducers -
* Object mapping action types to reducer functions. The result of the
* reducer is merged with the existing state.
*/ */
export function createReducer(actionToUpdateFn) { export function createReducer(reducers) {
return (state = {}, action) => { return (state = /** @type {State} */ ({}), action) => {
const fn = actionToUpdateFn[action.type]; const reducer = reducers[action.type];
if (!fn) { if (!reducer) {
return state; return state;
} }
const stateChanges = reducer(state, action);
// Some modules return an array rather than an object. They need to be // Some modules return an array rather than an object. They need to be
// handled differently so we don't cast them to an object. // handled differently so we don't convert them to an object.
if (Array.isArray(state)) { if (Array.isArray(stateChanges)) {
return [...fn(state, action)]; return stateChanges;
} }
return { return {
// @ts-expect-error - TS isn't certain `state` is spreadable here. Trust us!
...state, ...state,
...fn(state, action), ...stateChanges,
}; };
}; };
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment