Skip to content

Commit 81aacd9

Browse files
committed
Add logic to set deleted values in rhs to persist keys to undefined
1 parent 7492c87 commit 81aacd9

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/index.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,21 @@ const diff = (lhs, rhs) => {
55

66
if (typeof rhs !== 'object' || rhs === null) return rhs;
77

8-
return Object.keys(rhs).reduce((acc, key) => {
8+
const rhsKeys = Object.keys(rhs);
9+
10+
const deletedValues = Object.keys(lhs).reduce((acc, key) => {
11+
return rhsKeys.indexOf(key) !== -1 ? acc : { ...acc, [key]: undefined };
12+
}, {});
13+
14+
return rhsKeys.reduce((acc, key) => {
915
if (!lhs.hasOwnProperty(key)) return { ...acc, [key]: rhs[key] };
1016

1117
const lhsValue = lhs[key];
1218
const rhsValue = rhs[key];
1319
if (isEqual(lhsValue, rhsValue)) return acc;
1420

1521
return { ...acc, [key]: diff(lhsValue, rhsValue) };
16-
}, {});
22+
}, deletedValues);
1723
};
1824

1925
export default diff;

src/index.spec.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,16 @@ describe('.diff', () => {
5454
});
5555

5656
it('returns subset of right hand side value when a key value has been deleted', () => {
57-
expect(diff({ a: { b: 1 }, c: 2, d: { e: 100 } }, { a: { b: 1 }, c: 2, d: {} })).to.deep.equal({ d: {} });
57+
expect(diff({ a: { b: 1 }, c: 2, d: { e: 100 } }, { a: { b: 1 }, c: 2, d: {} })).to.deep.equal({ d: { e: undefined } });
5858
});
5959

6060
it('returns subset of right hand side value when a key value has been added', () => {
6161
expect(diff({ a: 1 }, { a: 1, b: 2 })).to.deep.equal({ b: 2 });
6262
});
63+
64+
it('returns keys as undefined when deleted from right hand side', () => {
65+
expect(diff({ a: 1, b: { c: 2 }}, { a: 1 })).to.deep.equal({ b: undefined });
66+
});
6367
});
6468

6569
describe('arrays', () => {
@@ -72,7 +76,7 @@ describe('.diff', () => {
7276
});
7377

7478
it('returns subset of right hand side array as object of indices to value when right hand side array has deletions', () => {
75-
expect(diff([1, 2, 3], [1, 3])).to.deep.equal({ 1: 3 });
79+
expect(diff([1, 2, 3], [1, 3])).to.deep.equal({ 1: 3, 2: undefined });
7680
});
7781

7882
it('returns subset of right hand side array as object of indices to value when right hand side array has additions', () => {

0 commit comments

Comments
 (0)