import { ActionOf, ActionCreator } from './actionCreatorFactory'; export type Mapper = (state: State, action: ActionOf) => State; export interface HandlerConfig { filter: ActionCreator; mapper: Mapper; } export interface AddHandler { addHandler: (config: HandlerConfig) => CreateReducer; } export interface CreateReducer extends AddHandler { create: () => Mapper; } export const reducerFactory = (initialState: State): AddHandler => { const allHandlerConfigs: Array> = []; const addHandler = (config: HandlerConfig): CreateReducer => { if (allHandlerConfigs.some(c => c.filter.type === config.filter.type)) { throw new Error(`There is already a handlers defined with the type ${config.filter.type}`); } allHandlerConfigs.push(config); return instance; }; const create = () => (state: State = initialState, action: ActionOf): State => { const handlerConfig = allHandlerConfigs.filter(config => config.filter.type === action.type)[0]; if (handlerConfig) { return handlerConfig.mapper(state, action); } return state; }; const instance: CreateReducer = { addHandler, create, }; return instance; };