From 01a37388521339a3e5d048d963f4d304d404cd7d Mon Sep 17 00:00:00 2001 From: Matt Phillips Date: Tue, 11 Apr 2017 21:05:02 +0100 Subject: [PATCH] Add proper object conversion to updated diff --- src/updated/index.js | 17 ++++++++++------- src/updated/index.test.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/src/updated/index.js b/src/updated/index.js index c98acd2..6a369f9 100644 --- a/src/updated/index.js +++ b/src/updated/index.js @@ -1,4 +1,4 @@ -import { isDate, isEmpty, isObject } from '../utils'; +import { isDate, isEmpty, isObject, properObject } from '../utils'; const updatedDiff = (lhs, rhs) => { @@ -6,15 +6,18 @@ const updatedDiff = (lhs, rhs) => { 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; diff --git a/src/updated/index.test.js b/src/updated/index.test.js index 0aee1ef..b88b47c 100644 --- a/src/updated/index.test.js +++ b/src/updated/index.test.js @@ -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') }); + }); + }); }); });