(initialState: S, ...ons: ReducerTypes<S, readonly ActionCreator[]>[])
| 112 | * ``` |
| 113 | */ |
| 114 | export function createReducer< |
| 115 | S, |
| 116 | A extends Action = Action, |
| 117 | // Additional generic for the return type is introduced to enable correct |
| 118 | // type inference when `createReducer` is used within `createFeature`. |
| 119 | // For more info see: https://github.com/microsoft/TypeScript/issues/52114 |
| 120 | R extends ActionReducer<S, A> = ActionReducer<S, A>, |
| 121 | >(initialState: S, ...ons: ReducerTypes<S, readonly ActionCreator[]>[]): R { |
| 122 | const map = new Map<string, OnReducer<S, ActionCreator[]>>(); |
| 123 | for (const on of ons) { |
| 124 | for (const type of on.types) { |
| 125 | const existingReducer = map.get(type); |
| 126 | if (existingReducer) { |
| 127 | const newReducer: typeof existingReducer = (state, action) => |
| 128 | on.reducer(existingReducer(state, action), action); |
| 129 | map.set(type, newReducer); |
| 130 | } else { |
| 131 | map.set(type, on.reducer); |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | return function (state: S = initialState, action: A): S { |
| 137 | const reducer = map.get(action.type); |
| 138 | return reducer ? reducer(state, action) : state; |
| 139 | } as R; |
| 140 | } |
no test coverage detected