concordancejs / concordance

Compare, format, diff and serialize any JavaScript value
ISC License
207 stars 15 forks source link

Sparse arrays are treated like arrays of undefined #74

Open ninevra opened 3 years ago

ninevra commented 3 years ago

concordance treats empty slots in arrays like undefined, for both formatting and comparison.

format(new Array(5)) gives

[
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
]

whereas util.inspect(new Array(5)) gives [ <5 empty items> ]

compare(new Array(5), Array.from({length: 5}) returns true, although these values behave rather differently.

novemberborn commented 3 years ago

Nice find! If we could detect the gap, we could encode a custom "empty primitive"?

ninevra commented 3 years ago

That would make sense to me. Detecting the gap is simple enough, just add if (current in this.value) {} around line 122 in https://github.com/concordancejs/concordance/blob/b30e7c8bdb19463b3a7e11d1dc8725affce7b059/lib/complexValues/object.js#L110-L123

I think any change here would probably(?) be breaking, though, since it would mean introducing a new descriptor tag, meaning old versions couldn't decode new serializations, and existing snapshots of sparse arrays would compare inequal to new snapshots of the same values.

There's also a test case asserting the current behavior at https://github.com/concordancejs/concordance/blob/b30e7c8bdb19463b3a7e11d1dc8725affce7b059/test/lodash-isequal-comparison.js#L135

I reviewed a few other libraries; it looks like chai, jest, and lodash all consider empty array items to equal undefined, while node's assert builtin module does not.

novemberborn commented 3 years ago

I think any change here would probably(?) be breaking, though, since it would mean introducing a new descriptor tag, meaning old versions couldn't decode new serializations, and existing snapshots of sparse arrays would compare inequal to new snapshots of the same values.

Yea. Let's see if we can get that into AVA 4 — and otherwise we can work out some compatibility between the different snapshot versions.

I reviewed a few other libraries; it looks like chai, jest, and lodash all consider empty array items to equal undefined, while node's assert builtin module does not.

I'm happy to follow assert, sparse arrays do behave differently so it seems useful to reflect that in snapshots and assertions.