import { Reducer , combineReducers , Action } from 'redux' ; import { ReducerManger , RootStoreState } from './types' ; type ReducerKey = keyof RootStoreState ; type ReducerMap = { [ key in keyof RootStoreState ] : Reducer ; } ; export function createReducerManager ( reducerMap ) { const reducers = { ... reducerMap , } ; let combinedReducer = combineReducers ( reducers ) ; let keysToRemove = [ ] ; return { reduce : ( state , action ) : RootStoreState => { if ( state && keysToRemove . length > 0 ) { state = { ... state } ; for ( let key of keysToRemove ) { delete state [ key ] ; } keysToRemove = [ ] ; } return combinedReducer ( state , action ) ; } , add : ( key , reducer ) => { if ( reducers [ key ] ) { return ; } reducers [ key ] = reducer ; combinedReducer = combineReducers ( reducers ) ; } , remove : ( key ) => { if ( ! reducers [ key ] ) { return ; } delete reducers [ key ] ; keysToRemove . push ( key ) ; combinedReducer = combineReducers ( reducers ) ; } , } ; }