Skip to content

Commit

Permalink
Fix the preserve array function with array of objects
Browse files Browse the repository at this point in the history
  • Loading branch information
popojargo committed Apr 20, 2019
1 parent 6296889 commit 0a40800
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/preserveArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { isObject } from './utils';
const getLargerArray = (l, r) => l.length > r.length ? l : r;

const preserve = (diff, left, right) => {

if (!isObject(diff)) return diff;
// Recursion stop conditions
// 1. The diff is not an object.
// 2. One of the side is undefined. Otherwise it causes errors
if (!isObject(diff) || left === undefined || right === undefined) return diff;

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

Expand Down
20 changes: 16 additions & 4 deletions src/preserveArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ import preserveArray from './preserveArray';

describe('.preserveArray', () => {
test('returns diff with nested objects converted back to arrays when property is deleted', () => {
const left = { a: [{ b: ['#', '#', '#', { hello: '' }] }, '#', { c: '', d: ['#', ''] }, '#'] };
const left = { a: [{ b: ['#', '#', '#', { hello: '' }, { hi: ''}] }, '#', { c: '', d: ['#', ''] }, '#'] };
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }] }, '#', { c: 'hello', d: ['#', 'bob'] }] };
const diff = {
a: {
0: {
b: {
3: {
hello: 'world'
}
},
4: undefined
}
},
2: {
Expand All @@ -31,7 +32,8 @@ describe('.preserveArray', () => {
'empty',
{
hello: 'world'
}
},
undefined
]
},
'empty',
Expand All @@ -42,6 +44,8 @@ describe('.preserveArray', () => {
undefined
]
};

// Remove 'empty'
delete expected.a[0].b[0];
delete expected.a[0].b[1];
delete expected.a[0].b[2];
Expand All @@ -53,13 +57,16 @@ describe('.preserveArray', () => {

test('returns diff with nested objects converted back to arrays when new property is added', () => {
const left = { a: [{ b: ['#', '#', '#', { hello: '' }] }, '#', { c: '', d: ['#', ''] }] };
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }] }, '#', { c: 'hello', d: ['#', 'bob'] }, 'foobar'] };
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }, {hi: ''}] }, '#', { c: 'hello', d: ['#', 'bob'] }, 'foobar'] };
const diff = {
a: {
0: {
b: {
3: {
hello: 'world'
},
4: {
hi: ''
}
}
},
Expand All @@ -81,6 +88,9 @@ describe('.preserveArray', () => {
'empty',
{
hello: 'world'
},
{
hi: ''
}
]
},
Expand All @@ -92,6 +102,8 @@ describe('.preserveArray', () => {
'foobar'
]
};

// Remove 'empty'
delete expected.a[0].b[0];
delete expected.a[0].b[1];
delete expected.a[0].b[2];
Expand Down

0 comments on commit 0a40800

Please sign in to comment.