|
| 1 | +import { Unsubscribe } from 'redux'; |
| 2 | + |
| 3 | +import { AppState, AppReducer, Action, AppReducerHash } from './redux-typings'; |
| 4 | + |
| 5 | +const reducers: Set<AppReducer> = new Set(); |
| 6 | + |
| 7 | +/** |
| 8 | + * Root reducer, used when creating the Redux store. |
| 9 | + * |
| 10 | + * The implementation simply invokes each registered `AppReducer` |
| 11 | + * in a loop. |
| 12 | + * |
| 13 | + * @param state Current application state. |
| 14 | + * @param action Action being dispatched. |
| 15 | + * |
| 16 | + * @returns New application state. |
| 17 | + */ |
| 18 | +export function rootReducer(state: AppState, action: Action): AppState { |
| 19 | + let newState = state; |
| 20 | + |
| 21 | + reducers.forEach((appReducer) => { |
| 22 | + newState = appReducer(newState, action); |
| 23 | + }); |
| 24 | + |
| 25 | + return newState; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Add given reducer to the list of registered application reducers. |
| 30 | + * |
| 31 | + * @param appReducer Reducer to add. |
| 32 | + * |
| 33 | + * @returns Function to remove (unsubscribe) the given reducer. |
| 34 | + */ |
| 35 | +export function addReducer(appReducer: AppReducer): Unsubscribe { |
| 36 | + reducers.add(appReducer); |
| 37 | + |
| 38 | + return () => { |
| 39 | + reducers.delete(appReducer); |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Remove all registered application reducers. |
| 45 | + * |
| 46 | + * *For testing purposes only.* |
| 47 | + */ |
| 48 | +export function clearReducers(): void { |
| 49 | + reducers.clear(); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Apply a collection of reducers, represented as `AppReducerHash`, |
| 54 | + * to compute new application state. |
| 55 | + * |
| 56 | + * The implementation looks for a key that matches action's `type`. |
| 57 | + * If present, the corresponding reducer is invoked to compute the |
| 58 | + * new state. Otherwise, original state is returned. |
| 59 | + * |
| 60 | + * @param reducerHash Reducer hash to use. |
| 61 | + * @param state Current application state. |
| 62 | + * @param action Action being dispatched. |
| 63 | + * |
| 64 | + * @returns New application state. |
| 65 | + */ |
| 66 | +export function applyReducerHash(reducerHash: AppReducerHash, state: AppState, action: Action): AppState { |
| 67 | + let newState = state; |
| 68 | + |
| 69 | + if (reducerHash.hasOwnProperty(action.type)) { |
| 70 | + newState = reducerHash[action.type](state, action); |
| 71 | + } |
| 72 | + |
| 73 | + return newState; |
| 74 | +} |
0 commit comments