Skip to content

Commit 9baaa46

Browse files
author
Phillip Clark
committed
Merge pull request #43 from joeldenning/issue35
Fix for issue #35 -- apply diffs for arrays
2 parents 25be3ea + 0ef4aeb commit 9baaa46

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

index.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@
249249
if (target && source && change && change.kind) {
250250
var it = target,
251251
i = -1,
252-
last = change.path.length - 1;
252+
last = change.path ? change.path.length - 1 : 0;
253253
while (++i < last) {
254254
if (typeof it[change.path[i]] === 'undefined') {
255255
it[change.path[i]] = (typeof change.path[i] === 'number') ? [] : {};
@@ -258,7 +258,7 @@
258258
}
259259
switch (change.kind) {
260260
case 'A':
261-
applyArrayChange(it[change.path[i]], change.index, change.item);
261+
applyArrayChange(change.path ? it[change.path[i]] : it, change.index, change.item);
262262
break;
263263
case 'D':
264264
delete it[change.path[i]];

test/tests.js

+18
Original file line numberDiff line numberDiff line change
@@ -482,4 +482,22 @@ describe('deep-diff', function() {
482482

483483
});
484484

485+
describe('regression test for bug #35', function() {
486+
var lhs = ["a", "a", "a"];
487+
var rhs = ["a"];
488+
489+
it('can apply diffs between two top level arrays', function() {
490+
var differences = deep.diff(lhs, rhs);
491+
492+
/* We must apply the differences in reverse order, since the array indices
493+
in the diff become stale/invalid if you delete elements from the array
494+
whose indices are in ascending order */
495+
for (var i = differences.length - 1; i >= 0; i--) {
496+
deep.applyChange(lhs, true, differences[i]);
497+
}
498+
499+
expect(lhs).to.eql(["a"]);
500+
});
501+
});
502+
485503
});

0 commit comments

Comments
 (0)