Skip to content

Commit

Permalink
Add proper object conversion to updated diff
Browse files Browse the repository at this point in the history
  • Loading branch information
mattphillips committed Apr 11, 2017
1 parent 142420f commit 01a3738
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/updated/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { isDate, isEmpty, isObject } from '../utils';
import { isDate, isEmpty, isObject, properObject } from '../utils';

const updatedDiff = (lhs, rhs) => {

if (lhs === rhs) return {};

if (!isObject(lhs) || !isObject(rhs)) return rhs;

if (isDate(lhs) || isDate(rhs)) {
if (lhs.toString() == rhs.toString()) return {};
return rhs;
const l = properObject(lhs);
const r = properObject(rhs);

if (isDate(l) || isDate(r)) {
if (l.toString() == r.toString()) return {};
return r;
}

return Object.keys(rhs).reduce((acc, key) => {
return Object.keys(r).reduce((acc, key) => {

if (lhs.hasOwnProperty(key)) {
const difference = updatedDiff(lhs[key], rhs[key]);
if (l.hasOwnProperty(key)) {
const difference = updatedDiff(l[key], r[key]);

if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc;

Expand Down
36 changes: 36 additions & 0 deletions src/updated/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,5 +103,41 @@ describe('.updatedDiff', () => {
expect(updatedDiff(new Date('2016'), new Date('2016'))).toEqual({});
});
});

describe('object create null', () => {
test('returns right hand side value when given objects are different at root', () => {
const lhs = Object.create(null);
lhs.a = 1;
const rhs = Object.create(null);
rhs.a = 2;
expect(updatedDiff(lhs, rhs)).toEqual({ a: 2 });
});

test('returns subset of right hand side value when sibling objects differ', () => {
const lhs = Object.create(null);
lhs.a = { b: 1 };
lhs.c = 2;
const rhs = Object.create(null);
rhs.a = { b: 1 };
rhs.c = 3;
expect(updatedDiff(lhs, rhs)).toEqual({ c: 3 });
});

test('returns subset of right hand side value when nested values differ', () => {
const lhs = Object.create(null);
lhs.a = { b: 1, c: 2 };
const rhs = Object.create(null);
rhs.a = { b: 1, c: 3 };
expect(updatedDiff(lhs, rhs)).toEqual({ a: { c: 3 } });
});

test('returns subset of right hand side with updated date', () => {
const lhs = Object.create(null);
lhs.date = new Date('2016');
const rhs = Object.create(null);
rhs.date = new Date('2017');
expect(updatedDiff(lhs, rhs)).toEqual({ date: new Date('2017') });
});
});
});
});

0 comments on commit 01a3738

Please sign in to comment.