import { Action , State } from "./types" ; export const generateId = ( ) => { return `${ Math . ceil ( Math . random ( ) * 1000000 ) }` ; } ; export const reducer = < T > ( defaultValue ) => { return ( state , action ) : State < T > => { const defaultValues = { isFocussed : false , wasTouched : false , error : undefined , value : defaultValue , id : generateId ( ) } ; switch ( action . type ) { case "APPEND_ITEM" : return [ ... state , { ... defaultValues , wasTouched : true } , ] ; case "INSERT_ITEM" : const [ before , after ] = [ state . slice ( 0 , action . index ) , state . slice ( action . index ) ] ; const newItem = { ... defaultValues , ... ( action . data ?? { } ) } ; return [ ... before , newItem , ... after ] ; case "REMOVE_ITEM" : return state . filter ( ( _ , i ) => i != action . index ) ; case "UPDATE_ITEM" : { const values = [ ... state ] ; values [ action . index ] = { ... values [ action . index ] , ... action . updates , } ; return values ; } case "UPDATE_ITEMS" : { const values = [ ... state ] . map ( ( x , i ) => { return { ... x , ... action . updates [ i ] } ; } ) ; return values ; } case "RESET" : { const values = [ ... state ] ; values [ action . index ] = { ... defaultValues , value : action . value } ; return values ; } case "RESET_ALL" : return action . values . map ( ( val ) => ( { ... defaultValues , value : val , } ) ) ; default : return state ; } } ; } ;