Immutable JavaScript object updater (simple implementation)
import equal from 'deep-equal' | |
export function immutableUpdate( obj, change ) { | |
const keys = Object.keys( change ) | |
if ( keys.length === 0 ) { | |
return obj | |
} | |
const key = keys[ 0 ] | |
const value = change[ key ] | |
if ( keys.length === 1 ) { | |
if ( !key ) { | |
return obj | |
} | |
if ( !obj ) { | |
return { [ key ]: value } | |
} | |
// if value is undefined delete it if it exists | |
if ( value === undefined ) { | |
const newObj = Object.assign( {}, obj ) | |
delete newObj[ key ] | |
return newObj | |
} | |
const current = obj[ key ] | |
if ( current && equal( current, value ) ) { | |
return obj | |
} | |
return Object.assign( {}, obj, { [ key ]: value } ) | |
} | |
const tail = Object.assign( {}, change ) | |
delete tail[ key ] | |
// TODO: fold/reduce/make tail recursive | |
return updateObject( updateObject( obj, { [ key ]: value } ), tail ) | |
} | |
export function updateAtom( current, update ) { | |
if ( update === undefined ) { return current } | |
return equal( current, update ) ? current : update | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment