|
| 1 | +import type { NoInfer } from './createStore' |
| 2 | +import type { Action } from './types/actions' |
| 3 | +import type { Reducer } from './types/reducers' |
| 4 | + |
| 5 | +/** |
| 6 | + * Composes multiple reducers into one. |
| 7 | + * |
| 8 | + * @param initialState The initial state, which can be a different preloaded state. |
| 9 | + * @param reducer The first reducer. Can accept a different preloaded state. |
| 10 | + * @param reducers The rest of the reducers. |
| 11 | + * @returns A reducer function that invokes every reducer passed in order, and returns the result of the last reducer. |
| 12 | + */ |
| 13 | +export default function reduceReducers< |
| 14 | + S, |
| 15 | + A extends Action, |
| 16 | + Actions extends Action[], |
| 17 | + P |
| 18 | +>( |
| 19 | + initialState: NoInfer<P | S> | undefined, |
| 20 | + reducer: Reducer<S, A, P>, |
| 21 | + ...reducers: { |
| 22 | + [K in keyof Actions]: Reducer<S, Actions[K]> |
| 23 | + } |
| 24 | +): Reducer<S, A | Actions[number], P> |
| 25 | +/** |
| 26 | + * Composes multiple reducers into one. |
| 27 | + * |
| 28 | + * @param reducer The first reducer. Can accept a different preloaded state. |
| 29 | + * @param reducers The rest of the reducers. |
| 30 | + * @returns A reducer function that invokes every reducer passed in order, and returns the result of the last reducer. |
| 31 | + */ |
| 32 | +export default function reduceReducers< |
| 33 | + S, |
| 34 | + A extends Action, |
| 35 | + Actions extends Action[], |
| 36 | + P |
| 37 | +>( |
| 38 | + reducer: Reducer<S, A, P>, |
| 39 | + ...reducers: { |
| 40 | + [K in keyof Actions]: Reducer<S, Actions[K]> |
| 41 | + } |
| 42 | +): Reducer<S, A | Actions[number], P> |
| 43 | +export default function reduceReducers<S, A extends Action, P>( |
| 44 | + ...args: [P | S | undefined | Reducer<S, A, P>, ...Array<Reducer<S, A>>] |
| 45 | +): Reducer<S, A, P> { |
| 46 | + const initialState = |
| 47 | + typeof args[0] === 'function' |
| 48 | + ? undefined |
| 49 | + : (args.shift() as P | S | undefined) |
| 50 | + const [firstReducer, ...restReducers] = args as [ |
| 51 | + Reducer<S, A, P>, |
| 52 | + ...Reducer<S, A>[] |
| 53 | + ] |
| 54 | + return (state = initialState, action) => |
| 55 | + restReducers.reduce( |
| 56 | + (state, reducer) => reducer(state, action), |
| 57 | + firstReducer(state, action) |
| 58 | + ) |
| 59 | +} |
0 commit comments