Skip to content
This repository was archived by the owner on Mar 6, 2018. It is now read-only.

squash patch - WIP #17

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ Because `buildRevertPatch + apply` offers more flexibility over `revert` it is p
* use [pack/unpack](#patch-size) with the result of `buildRevertPatch` making it ideal for storage or transport
* reverse a revert (and so on...) with `{reversible: true}`
* [diff](#diff) between reverts
* merge multiple reverts into one
* rebase reverts
* concat, squash, rebase multiple reverts

[↑](#json8-patch)

Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ module.exports.unpack = require('./lib/unpack')

// Utilities
module.exports.concat = require('./lib/concat')
module.exports.squash = require('./lib/squash')
56 changes: 56 additions & 0 deletions lib/squash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict'

function wasModified(patch, path) {
for (var i = 0; i < patch.length; i++) {
var op = patch[i]
if (op.path !== path) continue
if (op.op === 'add' || op.op === 'replace' || op.op === 'remove' || op.op === 'move' || op.op === 'copy') return true
}
return false
}

module.exports = function squash(patch) {
var squashed = []

var push = true

patch.forEach(function(op) {
// if current op overrides previous operations, remove them
if (['add', 'replace', 'remove', 'move', 'copy'].indexOf(op.op) !== -1) {
squashed.forEach(function(prev, idx) {
if (prev.op === 'test') return
if (prev.path === op.path) { // same path - FIXME children/parents ?
if (wasModified(squashed, op.path)) {
squashed[idx] = undefined
}

// the path was created in the patch, the remove operation shouldn't be included
// example
// {"path": "/foo", "op": "add", "value": "foo"},
// {"path": "/foo", "op": "remove"}
if (op.op === 'remove') {
push = false
}
// the path was created in the patch, replace op requires the target to exist
// example
// {"path": "/foo", "op": "add", "value": "foo"},
// {"path": "/foo", "op": "replace", "value": "bar"}
else if (op.op === 'replace') {
// push = false
op = {"path": op.path, "op": "add", "value": op.value}
}
}
})
}

if (push) {
squashed.push(op)
}
})

var foo = []
squashed.forEach(function(op) {
if (op !== undefined) foo.push(op)
})
return foo
}
Loading