Last active
October 24, 2018 14:26
-
-
Save aleclarson/b9ca24706cabd4f8cc0fed20614abeba to your computer and use it in GitHub Desktop.
deepCompare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { toString } = Object.prototype | |
/** Any object type */ | |
type AnyObj = { [key: string]: any } | |
export function deepCompare(a: any, b: any): boolean { | |
// Strict equality | |
if (a === b) return true | |
// Some types get special treatment | |
if (a && a.constructor == b.constructor && typeof a == 'object') { | |
switch (toString.call(a).slice(8, -1)) { | |
case 'Array': | |
return arrayCompare(a, b) | |
case 'Object': | |
return objectCompare(a, b) | |
case 'Date': | |
return +a === +b | |
case 'RegExp': | |
return a.toString() == b.toString() | |
} | |
} | |
// NaN equality | |
return a !== a && b !== b | |
} | |
function arrayCompare(a: any[], b: any[]): boolean { | |
let len = a.length | |
if (len != b.length) return false | |
for (let i = 0; i < len; i++) { | |
if (!deepCompare(a[i], b[i])) return false | |
} | |
return true | |
} | |
function objectCompare(a: AnyObj, b: AnyObj): boolean { | |
let ak = Object.keys(a) | |
let bk = Object.keys(b) | |
let len = ak.length | |
if (len != bk.length) return false | |
for (let i = 0; i < len; i++) { | |
let key = ak[i] | |
if (bk.indexOf(key) == -1) return false | |
} | |
for (let i = 0; i < len; i++) { | |
let key = bk[i] | |
if (ak.indexOf(key) == -1 || !deepCompare(a[key], b[key])) return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment