Skip to content

Instantly share code, notes, and snippets.

@szoio
Created November 11, 2018 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szoio/c2d26c6a8ddac508bb4eb8ea1e5974d7 to your computer and use it in GitHub Desktop.
Save szoio/c2d26c6a8ddac508bb4eb8ea1e5974d7 to your computer and use it in GitHub Desktop.
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