license import { Action } from "../Action" ; import { Reducer } from "../Reducer" ; import { TypedAction } from "../TypedAction" ; import { TypedActionDefinition2 } from "../TypedActionDefinition2" ; import { TypedActionString } from "../TypedActionString" ; import { TypedReducer } from "../TypedReducer" ; export class TypedReducerBuilderImpl < S > implements TypedReducer . Builder < S > { private typedHandlers : { [ type ] : Reducer < S > ; } = { } ; private defaultHandler : Reducer < S > | undefined ; withHandler < T > ( type , handler ) { return this . withActionHandler ( type , ( state , action ) => { return handler ( state , action . payload , action . meta ) ; } ) ; } withDefinitionHandler < T , E extends string = string > ( type , handler ) { return this . withHandler ( type . TYPE , handler ) ; } withActionHandler < T , E extends string = string > ( type , handler ) { if ( this . typedHandlers [ type as string ] ) { if ( process . env . NODE_ENV === "production" ) { console . error ( `Multiple typed reducer handlers specified in typed reducer for type ${ type }. Using newer.` ) ; } else { throw new Error ( `Multiple typed reducer handlers specified in typed reducer for type ${ type }.` ) ; } } this . typedHandlers [ type as string ] = handler as Reducer < S > ; return this ; } withDefaultHandler ( handler ) { if ( this . defaultHandler ) { if ( process . env . NODE_ENV === "production" ) { console . error ( "Multiple default handlers specified in typed reducer. Using newer." ) ; } else { throw new Error ( "Multiple default handlers specified in typed reducer." ) ; } } this . defaultHandler = handler ; return this ; } build ( ) { const defaultHandler = this . defaultHandler || ( ( state ) => state ) ; return new TypedReducerImpl < S > ( { ... this . typedHandlers } , defaultHandler ) . reduce ; } } class TypedReducerImpl < S > { private typedHandlers : { [ type ] : Reducer < S > ; } ; private defaultHandler : Reducer < S > ; constructor ( typedHandlers , defaultHandler ) { this . typedHandlers = typedHandlers ; this . defaultHandler = defaultHandler ; } reduce = ( state , action ) : S => { const typedHandler = this . typedHandlers [ action . type ] ; if ( typedHandler ) { return typedHandler ( state , action ) ; } else { return this . defaultHandler ( state , action ) ; } } ; }