isEqual issues
Describe the issue:
1. isEqual function goes into an infinite recursive loop if there are circular references.
let array1 = [1,2,3];
array1.push(array);
isEqual(array1, array2); // will go into an infinite loop
Possible solution
2. Should compare booleans
David's suggestion:
// First, a simple check for immutable types
if (
typeof itemA === 'string' ||
typeof itemA === 'number' ||
typeof itemA === 'boolean' ||
!itemA // falsey value
) {
if (itemA === itemB) {
return true;
}
return false;
}
Concerns with that is we need to compare length first for speed:
if (itemA.length !== itemB.length) {
return false;
}
3. Better comparison of types
David's suggestion:
if ((typeof itemA) !== (typeof itemB)) {
return false;
}
This might work but:
const itemA = [ 1, 2, 3 ];
const itemB = { a: 'a', b: 'b', c: 'c' }
typeof itemA; // returns "object"
typeof itemB; // returns "object"
// null values also return "object" with typeof so this isn't a deep enough comparison.
if ( ( typeof itemA ) !== ( typeof itemB ) ) { /* returns false */ }
const typeA = Object.prototype.toString.call(itemA); // returns "[object Array]"
const typeB = Object.prototype.toString.call(itemB); // returns "[object Object]"
if ( typeA !== typeB ) { /* returns true */ }
4. Better handling of Arrays
David's suggestion:
if (Array.isArray(itemA) && Array.isArray(itemB)) {
for (let i = 0; i < itemA.length; i++) {
if (!isEqual(itemA[i], itemB[i])) {
return false;
}
}
return true;
}
5: handle functions so we don't convert functions to strings (slow)
My suggestion:
// Throw for functions
if (typeof itemA === 'function') {
throw new Error('Cannot compare functions');
}
Throw if pass a function before comparing the items.
6: Other concerns from David:
Missing cases when comparing objects: "For example, if itemA has {A: 1} and itemB has {A: 1, B: 2}, it will return true."
also: we should name it something less ambiguous, like "deepCompare". "isEqual" could be interpretted as shallowCompare, which already exists in object.ts.
I would be very leery of scenarios where we actually need deepCompare though. It's a performance hazard, and potentially could get you into infinite loops.
I would not throw on a function comparison. I would do a reference compare. Or consider ignoring.
cc: @dzearing We may want to revert this and use lodash.isequal instead... https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.isequal/index.js
@dzearing Have you looked at the test file? Some of your concerns (like objects of different lengths) have tests and it does what I expect.
Closing this as we don't feel the need for this specific function anymore.