Skip to content

Commit

Permalink
use JSON.stringify as default hash for all non-primitive array elements
Browse files Browse the repository at this point in the history
following discussion at cujojs#32
  • Loading branch information
EyalAr committed Jan 13, 2016
1 parent afe905d commit 3195639
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/jsonPatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@ function patchInPlace(changes, x, options) {
}

function defaultHash(x) {
return isValidObject(x) ? JSON.stringify(x) : x;
return isValidObject(x) || isArray(x) ? JSON.stringify(x) : x;
}

function isValidObject (x) {
return x !== null && Object.prototype.toString.call(x) === '[object Object]';
}

function isArray (x) {
return Object.prototype.toString.call(x) === '[object Array]';
}
29 changes: 29 additions & 0 deletions test/jiff-test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
var buster = require('buster');
require('gent/test-adapter/buster');
var assert = buster.referee.assert;
var refute = buster.referee.refute;
var gent = require('gent');
var json = require('gent/generator/json');
var deepEquals = require('../lib/deepEquals');
Expand Down Expand Up @@ -91,6 +92,34 @@ buster.testCase('jiff', {
assert.equals(patch[0].op, 'add');
assert(patch[0].path === '/-' || patch[0].path === '/0');
assert.same(patch[0].value, 1);
},
'with default hash function': {
'primitives as elements': {
'should generate an empty patch when elements are equal': function() {
var patch = jiff.diff([1,'a',true], [1,'a',true]);
assert.equals(patch.length, 0);
}
},
'arrays as elements': {
'should generate an empty patch when elements are equal': function() {
var patch = jiff.diff([['a'],['b'],['c']], [['a'],['b'],['c']]);
assert.equals(patch.length, 0);
}
},
'objects as elements': {
'object keys with consistent order': {
'should generate an empty patch when elements are equal': function() {
var patch = jiff.diff([{a:'a',b:'b',c:'c'}], [{a:'a',b:'b',c:'c'}]);
assert.equals(patch.length, 0);
}
},
'object keys with inconsistent order': {
'should generate a non empty patch even though elements are equal': function() {
var patch = jiff.diff([{b:'b',c:'c',a:'a'}], [{a:'a',b:'b',c:'c'}]);
refute.equals(patch.length, 0);
}
}
}
}
},

Expand Down

0 comments on commit 3195639

Please sign in to comment.