Skip to content

Commit 0a40800

Browse files
committed
Fix the preserve array function with array of objects
1 parent 6296889 commit 0a40800

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

Diff for: src/preserveArray.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ import { isObject } from './utils';
33
const getLargerArray = (l, r) => l.length > r.length ? l : r;
44

55
const preserve = (diff, left, right) => {
6-
7-
if (!isObject(diff)) return diff;
6+
// Recursion stop conditions
7+
// 1. The diff is not an object.
8+
// 2. One of the side is undefined. Otherwise it causes errors
9+
if (!isObject(diff) || left === undefined || right === undefined) return diff;
810

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

Diff for: src/preserveArray.test.js

+16-4
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@ import preserveArray from './preserveArray';
22

33
describe('.preserveArray', () => {
44
test('returns diff with nested objects converted back to arrays when property is deleted', () => {
5-
const left = { a: [{ b: ['#', '#', '#', { hello: '' }] }, '#', { c: '', d: ['#', ''] }, '#'] };
5+
const left = { a: [{ b: ['#', '#', '#', { hello: '' }, { hi: ''}] }, '#', { c: '', d: ['#', ''] }, '#'] };
66
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }] }, '#', { c: 'hello', d: ['#', 'bob'] }] };
77
const diff = {
88
a: {
99
0: {
1010
b: {
1111
3: {
1212
hello: 'world'
13-
}
13+
},
14+
4: undefined
1415
}
1516
},
1617
2: {
@@ -31,7 +32,8 @@ describe('.preserveArray', () => {
3132
'empty',
3233
{
3334
hello: 'world'
34-
}
35+
},
36+
undefined
3537
]
3638
},
3739
'empty',
@@ -42,6 +44,8 @@ describe('.preserveArray', () => {
4244
undefined
4345
]
4446
};
47+
48+
// Remove 'empty'
4549
delete expected.a[0].b[0];
4650
delete expected.a[0].b[1];
4751
delete expected.a[0].b[2];
@@ -53,13 +57,16 @@ describe('.preserveArray', () => {
5357

5458
test('returns diff with nested objects converted back to arrays when new property is added', () => {
5559
const left = { a: [{ b: ['#', '#', '#', { hello: '' }] }, '#', { c: '', d: ['#', ''] }] };
56-
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }] }, '#', { c: 'hello', d: ['#', 'bob'] }, 'foobar'] };
60+
const right = { a: [{ b: ['#', '#', '#', { hello: 'world' }, {hi: ''}] }, '#', { c: 'hello', d: ['#', 'bob'] }, 'foobar'] };
5761
const diff = {
5862
a: {
5963
0: {
6064
b: {
6165
3: {
6266
hello: 'world'
67+
},
68+
4: {
69+
hi: ''
6370
}
6471
}
6572
},
@@ -81,6 +88,9 @@ describe('.preserveArray', () => {
8188
'empty',
8289
{
8390
hello: 'world'
91+
},
92+
{
93+
hi: ''
8494
}
8595
]
8696
},
@@ -92,6 +102,8 @@ describe('.preserveArray', () => {
92102
'foobar'
93103
]
94104
};
105+
106+
// Remove 'empty'
95107
delete expected.a[0].b[0];
96108
delete expected.a[0].b[1];
97109
delete expected.a[0].b[2];

0 commit comments

Comments
 (0)