import uuid from 'uuid' ; interface DocType { id : string ; type ? : string ; } const newFn = ( ) : DocType => ( { id : uuid . v1 ( ) } ) ; export interface CollectionActionsProps < T > { model : T ; name : keyof T ; onChange : ( partialModel : Partial < T > ) => void ; } export function handleChange < T , P extends DocType > ( props , doc ) { const { model , name } = props ; const collection = ( model [ name ] as unknown as DocType [ ] ) || [ ] ; const part = { [ name ] : collection . map ( ( row ) => ( row . id === doc . id ? doc : row ) ) } ; props . onChange ( { ... model , ... part } ) ; } export function handleDelete < T , P extends DocType > ( props , doc ) { const { model , name } = props ; const collection = ( model [ name ] as unknown as DocType [ ] ) || [ ] ; const part = { [ name ] : collection . filter ( ( row ) => row . id !== doc . id ) } ; props . onChange ?. ( { ... model , ... part } ) ; } export function handleAdd < T > ( props , fn = newFn ) { const { model , name } = props ; const collection = ( model [ name ] as unknown as DocType [ ] ) || [ ] ; const part = { [ name ] : collection . concat ( [ fn ( ) ] ) } ; props . onChange ?. ( { ... model , ... part } ) ; } export const collectionActions = { handleAdd , handleDelete , handleChange } ;