JSON-Patch icon indicating copy to clipboard operation
JSON-Patch copied to clipboard

Inefficient patch encoding when prepending to arrays

Open stbrody opened this issue 4 years ago • 2 comments

When adding an element to the beginning of an array, the resulting patch contains the full contents of the array, thus the storage requirements of the resulting patch scales with the size of the original array, not with the size of the diff between the arrays. Compare this with adding an element to the end of an array, where the resulting patch only contains data that scales with the size of the new element being added.

> fjp = require('fast-json-patch')
> fjp.compare(['foo', 'bar'], ['foo', 'bar', 'baz'])
[ { op: 'add', path: '/2', value: 'baz' } ]
> fjp.compare(['foo', 'bar'], ['baz', 'foo', 'bar'])
[
  { op: 'replace', path: '/1', value: 'foo' },
  { op: 'replace', path: '/0', value: 'baz' },
  { op: 'add', path: '/2', value: 'bar' }
]

stbrody avatar Sep 13 '21 20:09 stbrody

not only at the beginning, but at any position.

const fjp = require('fast-json-patch');
fjp.compare([1, 3], [1, 2, 3]);

/**
this will result 

[
  {
    "op": "replace",
    "path": "/1",
    "value": 2
  },
  {
    "op": "add",
    "path": "/2",
    "value": 3
  }
]
*/

holynewbie avatar Apr 19 '22 02:04 holynewbie

Hi, just wondering if there's any update on this? It seems like it should be possible to encode these types of updates more efficiently, for example with a new "insert" operator that just takes the value and array index to insert the value at, and implicitly pushes back the index of all later elements in the array.

stbrody avatar Oct 02 '22 17:10 stbrody