Skip to content

Commit

Permalink
Generate numeric array index===length when appending exactly to end o…
Browse files Browse the repository at this point in the history
…f array. Allowed by the rfc, and removes an extra comparison. Other minor cleanup
  • Loading branch information
briancavalier committed Apr 26, 2014
1 parent cc711b4 commit 2253ad4
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 10 deletions.
10 changes: 4 additions & 6 deletions jiff.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function appendListChanges(a1, a2, path, state) {
}

function lcsToJsonPatch(a1, a2, path, state, lcsMatrix) {
lcs.reduce(function(state, op, i, j) {
return lcs.reduce(function(state, op, i, j) {
var last, p;
if (op.type == lcs.REMOVE) {
p = path + '/' + j;
Expand All @@ -100,21 +100,19 @@ function lcsToJsonPatch(a1, a2, path, state, lcsMatrix) {
}
} else if (op.type == lcs.ADD) {
// See https://tools.ietf.org/html/rfc6902#section-4.1
// Must use '-' to indicate appending to array
p = path + '/' + (j === a1.length ? '-' : j);
// May use either index===length *or* '-' to indicate appending to array
state.patch.push({
op: 'add',
path: p,
path: path + '/' + j,
value: a2[i]
});
} else {
appendChanges(a1[j], a2[i], path + '/' + j, state);
}

return state;
}, state, lcsMatrix);

return state;
}, state, lcsMatrix);
}

function appendValueChanges(a, b, path, state) {
Expand Down
4 changes: 2 additions & 2 deletions lib/jsonPatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ function patch(changes, x) {
}

function patchInPlace(changes, x) {
if(!Array.isArray(changes) || changes.length === 0) {
// TODO: Consider throwing if changes is not an array
if(!Array.isArray(changes)) {
return x;
}

return changes.reduce(function(x, change) {
// TODO: Throw if unsupported or invalid op
var op = ops[change.op];
if(typeof op === 'function') {
x = op(x, change);
Expand Down
4 changes: 2 additions & 2 deletions test/jiff-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ buster.testCase('jiff', {

'diff': {
'on arrays': {
'should generate - for path suffix when appending': function() {
'should generate - or length for path suffix when appending': function() {
var patch = jiff.diff([], [1]);
assert.equals(patch[0].op, 'add');
assert.equals(patch[0].path, '/-');
assert(patch[0].path === '/-' || patch[0].path === '/0');
assert.same(patch[0].value, 1);
}
}
Expand Down

0 comments on commit 2253ad4

Please sign in to comment.