Skip to content

Instantly share code, notes, and snippets.

@paul-em
Last active February 2, 2017 22:22
Show Gist options
  • Save paul-em/b96674fa4113a80f4573b39e383d8dcd to your computer and use it in GitHub Desktop.
Save paul-em/b96674fa4113a80f4573b39e383d8dcd to your computer and use it in GitHub Desktop.
/**
*
* This will deep check two variables including objects
* Note: equals(NaN, NaN) uses js default behaviour: false
*
* equals(1, 1) --> true
* equals(1, 2) --> false
*
* equals({a: 1}, {a: 1}) --> true
* equals({a: 1}, {a: 2}) --> false
*
* equals({a: [{b: 2}]}, {a: [{b: 2}]}) --> true
* equals({a: [{b: 2}]}, {a: [{b: 3}]}) --> false
*
* equals(new Date(1), new Date(1)) --> true
* equals(new Date(1), new Date(2)) --> false
*
* @param o1 any value
* @param o2 any other value to compare to o1
* @returns {boolean}
*/
export function equals(o1, o2) {
if (o1 === o2) return true;
if (typeof o1 !== typeof o2 || !!o1 !== !!o2) return false;
if (Array.isArray(o1) !== Array.isArray(o2)) return false;
if (Array.isArray(o1)) {
return o1.length === o2.length && !o1.some((o1Item, index) => !equals(o1Item, o2[index]));
} else if (typeof o1 === 'object') {
if (o1 instanceof Date) return o1.getTime() === o2.getTime();
const o1Keys = Object.keys(o1);
const o2Keys = Object.keys(o2);
return o1Keys.length === o2Keys.length && !o1Keys.some((o1Key) => !equals(o1[o1Key], o2[o1Key]))
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment