Created
August 12, 2019 13:00
-
-
Save dhargitai/79431a3cfa6352d6ed09f7a44b753bf2 to your computer and use it in GitHub Desktop.
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
private difference(object1, object2) { | |
if (!object2 || Object.prototype.toString.call(object2) !== '[object Object]') { | |
return object1; | |
} | |
const differences = {}; | |
let key; | |
const arraysMatch = (array1, array2) => { | |
if (array1.length !== array2.length) return false; | |
for (let i = 0; i < array1.length; i++) { | |
if (array1[i] !== array2[i]) return false; | |
} | |
return true; | |
}; | |
const compare = (item1, item2, compareKey) => { | |
const type1 = Object.prototype.toString.call(item1); | |
const type2 = Object.prototype.toString.call(item2); | |
if (type2 === '[object Undefined]') { | |
differences[compareKey] = null; | |
return; | |
} | |
if (type1 !== type2) { | |
differences[compareKey] = item2; | |
return; | |
} | |
if (type1 === '[object Object]') { | |
const objectDifference = this.difference(item1, item2); | |
if (Object.keys(objectDifference).length > 1) { | |
differences[compareKey] = objectDifference; | |
} | |
return; | |
} | |
if (type1 === '[object Array]') { | |
if (!arraysMatch(item1, item2)) { | |
differences[compareKey] = item2; | |
} | |
return; | |
} | |
if (type1 === '[object Function]') { | |
if (item1.toString() !== item2.toString()) { | |
differences[compareKey] = item2; | |
} | |
} else { | |
if (item1 !== item2 ) { | |
differences[compareKey] = item2; | |
} | |
} | |
}; | |
for (key in object1) { | |
if (object1.hasOwnProperty(key)) { | |
compare(object1[key], object2[key], key); | |
} | |
} | |
for (key in object2) { | |
if (object2.hasOwnProperty(key)) { | |
if (!object1[key] && object1[key] !== object2[key] ) { | |
differences[key] = object2[key]; | |
} | |
} | |
} | |
return differences; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment