Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.78k stars 215 forks source link

Inefficient patch encoding when prepending to arrays #282

Open stbrody opened 2 years ago

stbrody commented 2 years ago

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' }
]
holynewbie commented 2 years ago

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
  }
]
*/
stbrody commented 1 year ago

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.