Skip to content

Commit

Permalink
reverse diffs
Browse files Browse the repository at this point in the history
  • Loading branch information
dchester committed Sep 29, 2020
1 parent ed584f7 commit 021c446
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const diff = require('./diff');
const patch = require('./patch');
const reverse = require('./reverse');

module.exports = {
diff,
patch,
reverse,
};
47 changes: 47 additions & 0 deletions reverse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const { _clone, _objId } = require('./helpers');

function reverse(changes) {

const reversed = _clone(changes).reverse();

for (const change of reversed) {

if (change.op == 'add') {
change.op = 'remove';
const id = _objId(change.value);
if (id) {
change._index = change.path.split('/').pop();
change.path = change.path.replace(/\d+$/, `[${id}]`);
}

} else if (change.op == 'remove') {
change.op = 'add';
}

if ('_prev' in change) {
var _prev = change._prev;
}

if ('value' in change) {
var _value = change.value;
}

if (_prev === undefined) {
delete change.value;
} else {
change.value = _prev;
}

if (_value === undefined) {
delete change._prev;
} else {
change._prev = _value;
}

}

return reversed;

}

module.exports = reverse;
16 changes: 15 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const assert = require('assert');

const diff = require('./diff');
const patch = require('./patch');
const reverse = require('./reverse');

/* DIFF */

Expand All @@ -26,7 +27,7 @@ assert.deepEqual(
[ { op: 'remove', path: '/title', _prev: 'hello' } ]
);

// object property remove
// object property replace
assert.deepEqual(
diff({ id: 1, title: 'hello' }, { id: 1, title: 'salut' }),
[ { op: 'replace', path: '/title', value: 'salut', _prev: 'hello' } ]
Expand Down Expand Up @@ -147,6 +148,19 @@ assert.deepEqual(
);


/* REVERSE */

assert.deepEqual(
reverse(
[ { op: 'replace', path: '/name', value: 'henry', _prev: 'hank' } ]
),
[ { op: 'replace', path: '/name', value: 'hank', _prev: 'henry' } ]
);

assert.deepEqual(
reverse(
[ { op: 'add', path: '/names/0', value: { id: 38, name: 'henry' } } ]
),
[ { op: 'remove', path: '/names/[38]', _index: 0, _prev: { id: 38, name: 'henry' } } ]
);

0 comments on commit 021c446

Please sign in to comment.