import { atom } from '../atom-constructors' ; import { Atom , RemovableAtom , Updater } from '../types' ; export const getAtomAtKey = < O extends object , K extends keyof O > ( atomOfObject , key ) : RemovableAtom < O [ K ] > => { let cachedValue ; const keyIsRemoved = ( key ) => ! atomOfObject . getValue ( ) . hasOwnProperty ( key ) ; const newAtom = atom ( get => { if ( ! keyIsRemoved ( key ) ) { cachedValue = get ( atomOfObject ) [ key ] ; } return cachedValue ; } , ( update ) => { if ( ! keyIsRemoved ( key ) ) { const oldValue = atomOfObject . getValue ( ) [ key ] ; const newValue = update instanceof Function ? update ( oldValue ) : update ; atomOfObject . update ( oldObj => ( { ... oldObj , [ key ] : newValue , } ) ) ; } } ) ; return { ... newAtom , remove : ( ) => { atomOfObject . update ( oldObj => { const updatedObj = { ... oldObj } ; delete updatedObj [ key ] ; return updatedObj ; } ) ; } , } ; } ;