Skip to content

Preserve sparse array holes in cloneDeep - #6262

Open
TemRevil wants to merge 1 commit into
lodash:mainfrom
TemRevil:fix/clonedeep-sparse-array-holes
Open

TemRevil wants to merge 1 commit into
lodash:mainfrom
TemRevil:fix/clonedeep-sparse-array-holes

Conversation

@TemRevil

Copy link
Copy Markdown

Fixes #6191

_.cloneDeep on a sparse array currently fills every hole with an explicit undefined instead of leaving it empty, which diverges from native structuredClone.

The array branch in baseClone iterates every index from 0 to length-1 and always calls assignValue, even when the source has no own property at that index. Skipping indices that are not own properties of the source keeps the clone's holes matching the original.

Repro from the issue:

let x = new Array(5);
x[3] = 42;
_.cloneDeep(x); // before: [undefined x3, 42, undefined], after: same holes as x

Added a regression test alongside the existing clone/cloneDeep tests. Ran the full suite locally (npm test), 6834/6834 passing, and jscs style checks clean on both lodash.js and test/test.js.

Scoped this to cloneDeep since that's what #6191 reports. _.clone (shallow) has the same underlying gap via copyArray, happy to follow up separately if that's wanted.

…ith undefined

baseClone's array loop iterated every index from 0 to length-1 and
always called assignValue, so indices with no own property (array
holes) were written as an explicit undefined on the clone. That
diverges from structuredClone, which leaves holes untouched.

Skip indices that are not own properties of the source array so the
new array keeps the same holes as the original.

Fixes lodash#6191
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 this pull request may close these issues.

cloneDeep wrongly applies <undefined> value to weak array elements; should stay <empty>!

1 participant