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 4 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
81 changes: 18 additions & 63 deletions packages/block-editor/src/utils/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,6 @@
import { paramCase } from 'change-case';
import memoize from 'memize';

/**
* Converts a path to an array of its fragments.
* Supports strings, numbers and arrays:
*
* 'foo' => [ 'foo' ]
* 2 => [ '2' ]
* [ 'foo', 'bar' ] => [ 'foo', 'bar' ]
*
* @param {string|number|Array} path Path
* @return {Array} Normalized path.
*/
function normalizePath( path ) {
if ( Array.isArray( path ) ) {
return path;
} else if ( typeof path === 'number' ) {
return [ path.toString() ];
}

return [ path ];
}

/**
* Converts any string to kebab case.
* Backwards compatible with Lodash's `_.kebabCase()`.
Expand Down Expand Up @@ -55,33 +34,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 +45,27 @@ 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 ) : {};
// Normalize path
path = Array.isArray( path ) ? path : [ path ];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use a new constant here? Mutation can introduce potential issues as we refactor in the future, and storing in a new constant is cheap.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not mutatating in this case, just reassigning

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Furthermore, I see we're ditching the numeric path support, and I confirm that this is fine. I can't think of a use case where it won't work properly without that specific handling that we used to do.


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;
// Shallowly clone the base of the object
object = Array.isArray( object ) ? [ ...object ] : { ...object };

// Traverse object from root to leaf, shallowly cloning at each level
let prev = object;
for ( const i in path ) {
const branch = path[ i ];
if ( i < path.length - 1 ) {
prev[ branch ] = Array.isArray( prev[ branch ] )
? [ ...prev[ branch ] ]
: { ...prev[ branch ] };
} else {
prev[ branch ] = value;
}
return acc[ key ];
}, newObject );
prev = prev[ branch ];
}

return newObject;
return object;
}

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