Skip to content

Commit

Permalink
compose reducer on the fly instead of storing reducer array
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaosiyang committed Sep 24, 2019
1 parent dcc72ee commit 8b31906
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions modules/store/src/reducer_creator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ActionCreator, ActionReducer, ActionType, Action } from './models';
import { compose } from './utils';

// Return type of the `on` fn.
export interface On<S> {
Expand Down Expand Up @@ -229,25 +230,22 @@ export function createReducer<S, A extends Action = Action>(
initialState: S,
...ons: On<S>[]
): ActionReducer<S, A> {
const map = new Map<string, ActionReducer<S, A>[]>();
const map = new Map<string, ActionReducer<S, A>>();
for (let on of ons) {
for (let type of on.types) {
if (map.has(type)) {
const existingReducers = map.get(type) as ActionReducer<S, A>[];
map.set(type, [...existingReducers, on.reducer]);
const existingReducer = map.get(type) as ActionReducer<S, A>;
const newReducer: ActionReducer<S, A> = (state, action) =>
on.reducer(existingReducer(state, action), action);
map.set(type, newReducer);
} else {
map.set(type, [on.reducer]);
map.set(type, on.reducer);
}
}
}

return function(state: S = initialState, action: A): S {
const reducers = map.get(action.type);
return reducers && reducers.length > 0
? reducers.reduce(
(previousState, reducer) => reducer(previousState, action),
state
)
: state;
const reducer = map.get(action.type);
return reducer ? reducer(state, action) : state;
};
}

0 comments on commit 8b31906

Please sign in to comment.