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 3 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
76 changes: 12 additions & 64 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,20 @@ 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 = 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.


if ( path.length === 0 ) {
return value;
}

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 ] = setImmutably( shallowClone[ first ], rest, value );
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a way to achieve the same without recursivity? I think recursivity has a performance overhead that is best avoided in low level functions that get called often.

Copy link
Member Author

Choose a reason for hiding this comment

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

Unlike cloneObjects, which was using a recursive function in for every object inside, this one is only called for every item in the path though. But I can check.

Copy link
Contributor

Choose a reason for hiding this comment

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

ChatGPT gave me this, is that equivalent :P

export function setImmutably(object, path, value) {
  path = Array.isArray(path) ? path : [path];

  if (path.length === 0) {
    return value;
  }

  const shallowClone = Array.isArray(object)
    ? [...object]
    : { ...object };
  let currentObj = shallowClone;

  for (let i = 0; i < path.length - 1; i++) {
    const key = path[i];
    currentObj = currentObj[key] && typeof currentObj[key] === 'object'
      ? { ...currentObj[key] }
      : {};
    currentObj[key] = currentObj;
  }

  currentObj[path[path.length - 1]] = value;

  return shallowClone;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm guessing it's wrong for nested arrays.

Copy link
Member Author

Choose a reason for hiding this comment

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

The for loop is weird, it should be

	 for ( let i = 0; i < path.length - 1; i++ ) {
		const key = path[ i ];
		currentObj[ key ] = Array.isArray( currentObj[ key ] )
			? [ ...currentObj[ key ] ]
			: { ...currentObj[ key ] };
		currentObj = currentObj[ key ];
	}

Copy link
Member Author

Choose a reason for hiding this comment

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

The number of nested functions = path.length. Even if you'd do something like a forEach or reduce loop you'd have the same number of nested function. It really seems ok to me. We're not deep cloning here.

Copy link
Contributor

Choose a reason for hiding this comment

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

non-tail-recursive

yes, this is the main thing for me. I agree that it's harder to read and for this particular use-case, it might not be much recursivity (path is short in most cases), so I'm fine shipping this but I think in JavaScript specifically, it's best to avoid recursion. functions arguments get copied over and over again from caller to callee... and same for return values.

Copy link
Member

Choose a reason for hiding this comment

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

I spent some time looking at the original code and it used to do:

_.setWith( object ? _.clone( object ) : {}, path, value, _.clone )

That means that we indeed did only a shallow clone, and then a deep clone at the specified path.

Thanks for locating this discrepancy, it seems like we were way more opportunistic when we did the migration.

My take on the recursion approach here is that it will still be better than what we had before - always deep cloning the entire input object. I also find it quite more readable than the loop alternative.

Copy link
Contributor

Choose a reason for hiding this comment

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

Pushed 7bdcfd0

Copy link
Member Author

Choose a reason for hiding this comment

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

I tweaked it even further after that, I think it makes it more readable and avoids the if statement. Also cached prev[ key ]. Anyway at this point we're probably micro optimising for performance and readability. :)


return newObject;
return shallowClone;
}

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