import type { CreateReducerReturn, PayloadAction } from './createReducer' type Reducers = Record> type State = { [P in keyof TReducers]: TReducers[P]['initialState'] } type StateKey = keyof TReducers function applyReducers( state: TState, newState: Partial ): TState { for (const [key, value] of Object.entries(newState)) { const lookup = key as keyof typeof newState if (state[lookup] !== value) { return { ...state, ...newState, } } } return state } export function combineReducers( reducers: TReducers ) { const initialState: State = {} as any /* Prepare initial state as well as action mapping */ for (const [key, reducerConfig] of Object.entries(reducers)) { initialState[key as keyof typeof reducers] = reducerConfig.initialState } const reducer = (state: State, action: PayloadAction) => { const updatedState: Partial> = {} for (const [key, reducerConfig] of Object.entries(reducers)) { const typedKey: StateKey = key updatedState[typedKey] = reducerConfig.reducer( state[typedKey], action ) } return applyReducers(state, updatedState) } return { initialState, reducer, } }