DoneDeal0 / superdiff

Superdiff compares two arrays or objects and returns a full diff of their differences in a readable format.
https://www.npmjs.com/package/@donedeal0/superdiff
695 stars 6 forks source link

Making array order optional #3

Closed AlexisAnzieu closed 1 year ago

AlexisAnzieu commented 1 year ago

Hey! Thanks for this excellent library! In one of my use case, I would need to compare two objects and mark them as equals no matter if the elements in their arrays are not in the same order. eg:

const objectA = {
          id: 54,
          user: {
            name: "joe",
           member: true,
          hobbies: ["golf", "football"],
            age: 66,
         },
  }

const objectB = {
        id: 54,
        user: {
            name: "joe",
           member: true,
           hobbies: [ "football", "golf"],
            age: 66,
        },
  }

  // Be marked as equal

Would it be possible to add this kind of option in the API? Thanks a lot!

DoneDeal0 commented 1 year ago

Hi @AlexisAnzieu ,

Thanks for your interest in Superdiff!

I hesitated before adding such an option, because it slows the diff down a little bit. But we're talking about less than 10ms on thousands of objects, so I guess it's fine.

Anyways, getObjectDiff() now accept a facultative options parameter:

{
  discardArrayOrder?: boolean // false by default
}

If discardArrayOrder is set to true, ["hello", "world"] and ["world", "hello"] will be considered as equal, because the two arrays have the same value, just not in the same order.

Does it solve your issue?

AlexisAnzieu commented 1 year ago

Yes sounds perfect, thank you! By testing it a bit further I also noticed an odd behavior:

const a = {
    "boolean": false,
}

getObjectDiff(a, a)
 // output "updated"

const b = {
    "boolean": true,
}

getObjectDiff(b, b)
 // output "equal"

It seems that a condition is failing somewhere 🤔

AlexisAnzieu commented 1 year ago

it may come from there. Maybe if (!!!previousValue && typeof previousValue !== 'boolean') instead?

DoneDeal0 commented 1 year ago

There is always an edgecase despite all the tests^^. Well spotted! I'send the fix within 48 hours.

DoneDeal0 commented 1 year ago

Thank you again for spotting this error. The equality check was actually failing for all falsy values (undefined, null, false), in the main properties, but also in the subproperties diff. I can't believe I missed it.

The issue is now fixed (see #6 ), with related tests. The fix has been deployed in v1.0.7.

Please let me know if all's good for you.

AlexisAnzieu commented 1 year ago

All good! Thanks a lot 👌