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

cloneIfObject converts arrays to objects #385

Closed
twisty opened this issue Feb 12, 2020 · 5 comments · Fixed by #391
Closed

cloneIfObject converts arrays to objects #385

twisty opened this issue Feb 12, 2020 · 5 comments · Fixed by #391

Comments

@twisty
Copy link
Member

twisty commented Feb 12, 2020

If you pass an array into this function, it returns an object.

export function cloneIfObject(value: unknown) {
// Clone objects to avoid accidental param reassignment
return isObject(value) ? { ...value } : value;
}

This is because this function returns true when passed an array:

export function isObject(value: unknown): value is object {
return value !== null && typeof value === 'object';
}

(Try in browser console)

typeof []
> "object"

I'm not certain if arrays need to be cloned too, but a workaround is:

export function cloneIfObject(value: unknown) {
  // Clone objects to avoid accidental param reassignment
  if (isArray(value)) {
    return [...value];
  }
  return isObject(value) ? { ...value } : value;
}

...but then cloneIfObject isn't very well named!

@twisty
Copy link
Member Author

twisty commented Feb 12, 2020

Maybe cloneIfMutable would be a better name?

@rkuykendall
Copy link
Member

@twisty Do you think this 'feature' of immutability is even worth keeping around considering this issue and #379 ?

@rkuykendall
Copy link
Member

It seems like what we want for this check is less like isObject which returns true for arrays?!?! and more like isPlainObject which would also fix the moment bug. https://github.com/lodash/lodash/blob/aa1d7d870d9cf84842ee23ff485fd24abf0ed3d1/isPlainObject.js#L30

@twisty
Copy link
Member Author

twisty commented Feb 12, 2020

isPlainObject makes sense.

I would have no problem if the cloning was ditched. It would then just be up to the user to handle immutability themselves when they call setValue.

If we do keep the cloning, we should deal with the arrays properly, though!

@rkuykendall
Copy link
Member

Released:

v2.0.1

v2.0.0...v2.0.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants