Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created March 22, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mscalora/ae1b0267fd0e5679da143fa1a8f6ccbf to your computer and use it in GitHub Desktop.
Save mscalora/ae1b0267fd0e5679da143fa1a8f6ccbf to your computer and use it in GitHub Desktop.
// From: NicolasLetellier @ https://gist.github.com/Yimiprod/7ee176597fef230d1451#gistcomment-3058093
function objectDiff(object, base) {
function changes(object, base) {
const accumulator = {};
Object.keys(base).forEach((key) => {
if (object[key] === undefined) {
accumulator[`-${key}`] = base[key];
}
});
return _.transform(
object,
(accumulator, value, key) => {
if (base[key] === undefined) {
accumulator[`+${key}`] = value;
} else if (!_.isEqual(value, base[key])) {
accumulator[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
}
},
accumulator
);
}
return changes(object, base);
}
/**
* create object that reflects the difference where each primitive value is an array of the before and after values
* @param {object} before
* @param {object} after
* @returns {object}
*/
function objectDiffBeforeAfter(before, after) {
function changes(before, after) {
const accumulator = {};
Object.keys(after).forEach((key) => {
if (before[key] === undefined) {
accumulator[key] = [undefined, after[key]];
}
});
return _.transform(
before,
(accumulator, value, key) => {
if (after[key] === undefined) {
accumulator[key] = [value, undefined];
} else if (!_.isEqual(value, after[key])) {
accumulator[key] = (_.isObject(value) && _.isObject(after[key])) ? changes(value, after[key]) : [value, after[key]];
}
},
accumulator
);
}
return changes(before, after);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment