Created
September 14, 2017 21:56
-
-
Save AndrewHenderson/91382ebef37c03ecfe65e3a29e6d4d4d to your computer and use it in GitHub Desktop.
This file contains 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
iimport { | |
isArray, | |
isObject, | |
isNull, | |
isNil, | |
isEqual, | |
isUndefined, | |
keys, | |
uniq, | |
each, | |
times, | |
} from 'lodash'; | |
function isSameType(a, b) { | |
if (typeof a !== typeof b) { | |
return false; | |
} | |
if (isArray(a) && isArray(b)) { | |
return true; | |
} | |
if (isObject(a) && isArray(b)) { | |
return false; | |
} | |
if (isArray(a) && isObject(b)) { | |
return false; | |
} | |
if (isObject(a) && isNull(b)) { | |
return false; | |
} | |
if (isNull(a) && isObject(b)) { | |
return false; | |
} | |
return true; | |
} | |
function diff(a, b) { | |
if (isEqual(a, b)) { | |
return; | |
} | |
if (isUndefined(b)) { | |
return null; | |
} | |
if (!isSameType(a, b)) { | |
return b; | |
} | |
let _keys; | |
let output; | |
if (isArray(a)) { | |
if (isNil(b)) { | |
output = b; | |
} | |
const length = a.length >= b.length ? a.length : b.length; | |
times(length, function(index) { | |
const delta = diff(a[index], b[index]); | |
output = output || []; | |
if (isUndefined(delta)) { | |
output.push(undefined); | |
} else { | |
output.push(delta); | |
} | |
}); | |
} else if (isObject(a)) { | |
_keys = uniq(keys(a).concat(keys(b))); | |
each(_keys, function(key) { | |
const delta = diff(a[key], b[key]); | |
if (delta) { | |
output = output || {}; | |
output[key] = delta; | |
} | |
}); | |
} else { | |
if (!isEqual(a, b)) { | |
output = b; | |
} | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment