Skip to content

Instantly share code, notes, and snippets.

@zemlanin
Last active December 25, 2015 13:16
Show Gist options
  • Save zemlanin/95e94c33cc7556f606f0 to your computer and use it in GitHub Desktop.
Save zemlanin/95e94c33cc7556f606f0 to your computer and use it in GitHub Desktop.
// https://babeljs.io/repl/#?evaluate=true
function getDiff(that, other) {
if (that == other) { return {} }
if (_.isEmpty(other)) {
return {all: true}
}
if (_.isObject(that)) {
if (!_.isObject(other)) { return {all: true} }
const keysDiff = _.difference(_.keys(that), _.keys(other))
const keysDiffResult = _(keysDiff).map(k => [k, {all: true}]).zipObject().value()
const innerDiff = _(that)
.keys()
.map(k => [k, getDiff(that[k], other[k])])
.reject(([k, v]) => _.isEmpty(v))
.zipObject()
.value()
if (_.isEmpty(innerDiff) && _.isEmpty(keysDiffResult)) {
return {}
}
return {values: _.assign(innerDiff, keysDiffResult)}
}
return {all: true}
}
console.log(_([
[{a: 1}, null, {all: true}],
[{a: 1}, {}, {all: true}],
[{a: 1}, {a: 1}, {}],
[{a: 1}, {a: 2}, {"values": {"a": {"all": true}}}],
[{a: 1}, {b: 2}, {values: {a: {all: true}}}],
[{a: 1}, {a: {c: 2}}, {values: {a: {all: true}}}],
[{a: {c: 2}}, {a: {c: 2}}, {}],
[{a: {b: 2, d: 4}}, {a: {c: 2}}, {values: {a: {values: {b: {all: true}, d: {all: true}}}}} ],
[{a: {b: {d: 4}}}, {a: {b: {}}}, {"values":{"a":{"values":{"b":{"all":true}}}}} ],
[{a: {c: 2}}, {a: {b: 2, d: 4}}, {values: {a: {values: {c: {all: true}}}}}],
]).map(([a, b, res]) => _.isEqual(getDiff(a, b), res)
? 'ok'
: `getDiff(${JSON.stringify(a)}, ${JSON.stringify(b)}) != ${JSON.stringify(res)} || ${JSON.stringify(getDiff(a, b))}`).value().join('\n'),
'\n\n\n\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment