Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setImmutably: don't clone all objects #56612

Merged
merged 5 commits into from
Nov 30, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 14 additions & 43 deletions packages/block-editor/src/utils/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,33 +55,6 @@ export function kebabCase( str ) {
} );
}

/**
* Clones an object.
* Arrays are also cloned as arrays.
* Non-object values are returned unchanged.
*
* @param {*} object Object to clone.
* @return {*} Cloned object, or original literal non-object value.
*/
function cloneObject( object ) {
if ( Array.isArray( object ) ) {
return object.map( cloneObject );
}

if ( object && typeof object === 'object' ) {
return {
...Object.fromEntries(
Object.entries( object ).map( ( [ key, value ] ) => [
key,
cloneObject( value ),
] )
),
};
}

return object;
}

/**
* Immutably sets a value inside an object. Like `lodash#set`, but returning a
* new object. Treats nullish initial values as empty objects. Clones any
Expand All @@ -93,24 +66,22 @@ function cloneObject( object ) {
* @return {Object} Cloned object with the new value set.
*/
export function setImmutably( object, path, value ) {
const normalizedPath = normalizePath( path );
const newObject = object ? cloneObject( object ) : {};
path = normalizePath( path );

if ( path.length === 0 ) {
throw new Error( 'Path cannot be empty' );
}

const shallowClone = Array.isArray( object )
? [ ...object ]
: { ...object };
const [ first, ...rest ] = path;

normalizedPath.reduce( ( acc, key, i ) => {
if ( acc[ key ] === undefined ) {
if ( Number.isInteger( path[ i + 1 ] ) ) {
acc[ key ] = [];
} else {
acc[ key ] = {};
}
}
if ( i === normalizedPath.length - 1 ) {
acc[ key ] = value;
}
return acc[ key ];
}, newObject );
shallowClone[ first ] = rest.length
? setImmutably( shallowClone[ first ], rest, value )
: value;

return newObject;
return shallowClone;
}

const stringToPath = memoize( ( path ) => path.split( '.' ) );
Expand Down
Loading