← Back to JavaScript, page 10

javascript-0199 · Hard senior

How would you implement a JSON diff that produces patch operations, and a function that applies them?

Walk both values together. For objects, compare keys: removed keys become remove operations, new keys become add operations, and shared keys recurse. For arrays, compare by index and handle length changes. Describe each operation with a path in JSON Pointer form, apply patches without mutating the input, and test the property that apply(a, diff(a, b)) equals b, including a randomized round-trip test.

Full answer

A diff and patch pair is used for syncing state, audit logs, undo history, and sending small updates instead of whole documents. The standard format is JSON Patch (RFC 6902) with operations add, remove, and replace (also move, copy, and test), and paths written as JSON Pointers (RFC 6901).

Algorithm for the simple version:

  1. If both values are the same by Object.is, no operation.
  2. If both are plain objects: for every key only in a, emit remove. For every key only in b, emit add. For keys in both, recurse with the path extended by the key.
  3. If both are arrays: compare index by index for the shared length and recurse. If b is longer, emit add for new indexes. If b is shorter, emit remove for the extra indexes from the end to the start, so earlier removals do not shift later indexes.
  4. Otherwise (different types or different primitives), emit replace with the new value.

Details that matter:

  • JSON Pointer escaping: ~ becomes ~0 and / becomes ~1, so keys such as a/b are encoded correctly. The root path is the empty string.
  • Distinguish plain objects, arrays, and null (typeof null is 'object'). Dates and class instances are not JSON, so convert them first.
  • The index-based array diff is simple and can be wasteful. Inserting at the front produces many replaces. Smarter versions use a longest common subsequence or keys for items, and produce move operations.
  • Applying: copy the structure along the changed path instead of mutating the input (structural sharing keeps unchanged parts), apply operations in order, and fail clearly for a missing path. Add test operations when conflicts matter.
  • Values must be cloned into the patch, or later changes to the source object would change the patch.
  • Order matters: remove array items from the end, and apply object operations independent of order.
  • Large documents: avoid deep recursion limits, and consider hashing subtrees to skip equal parts.

Property test: for random pairs of documents, apply(a, diff(a, b)) must deep-equal b, and a must not change. This catches the most bugs, and is better than a few handwritten examples.

javascript
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
const escape = (key) => String(key).replaceAll('~', '~0').replaceAll('/', '~1');
const unescape = (key) => key.replaceAll('~1', '/').replaceAll('~0', '~');
const clone = (v) => structuredClone(v);

function diff(a, b, path = '', ops = []) {
  if (Object.is(a, b)) return ops;
  if (isObject(a) && isObject(b)) {
    for (const key of Object.keys(a)) if (!(key in b)) ops.push({ op: 'remove', path: `${path}/${escape(key)}` });
    for (const key of Object.keys(b)) {
      if (!(key in a)) ops.push({ op: 'add', path: `${path}/${escape(key)}`, value: clone(b[key]) });
      else diff(a[key], b[key], `${path}/${escape(key)}`, ops);
    }
  } else if (Array.isArray(a) && Array.isArray(b)) {
    const shared = Math.min(a.length, b.length);
    for (let i = 0; i < shared; i++) diff(a[i], b[i], `${path}/${i}`, ops);
    for (let i = shared; i < b.length; i++) ops.push({ op: 'add', path: `${path}/${i}`, value: clone(b[i]) });
    for (let i = a.length - 1; i >= b.length; i--) ops.push({ op: 'remove', path: `${path}/${i}` });
  } else {
    ops.push({ op: 'replace', path, value: clone(b) });
  }
  return ops;
}

function applyPatch(doc, ops) {
  let result = clone(doc);
  for (const { op, path, value } of ops) {
    if (path === '') {
      result = clone(value);
      continue;
    }
    const keys = path.split('/').slice(1).map(unescape);
    const last = keys.pop();
    let parent = result;
    for (const key of keys) {
      if (parent == null || !(key in Object(parent))) throw new Error(`path not found: ${path}`);
      parent = parent[key];
    }
    if (parent == null || typeof parent !== 'object') throw new Error(`path not found: ${path}`);
    if (Array.isArray(parent)) {
      const index = last === '-' ? parent.length : Number(last);
      if (op === 'remove') parent.splice(index, 1);
      else if (op === 'add') parent.splice(index, 0, clone(value));
      else parent[index] = clone(value);
    } else if (op === 'remove') delete parent[last];
    else parent[last] = clone(value);
  }
  return result;
}

const before = { name: 'Asha', tags: ['a', 'b', 'c'], address: { city: 'Pune', zip: '411001' }, 'a/b': 1, 'x~y': 2 };
const after = { name: 'Asha K', tags: ['a', 'z'], address: { city: 'Pune', country: 'IN' }, 'a/b': 2, 'x~y': 2, extra: [1] };
const patch = diff(before, after);
console.log(patch.map((o) => `${o.op} ${o.path}` + ('value' in o ? ' = ' + JSON.stringify(o.value) : '')).join('\n'));

const rebuilt = applyPatch(before, patch);
console.log('round trip equal:', JSON.stringify(rebuilt) === JSON.stringify(after), '| input unchanged:', before.tags.length === 3 && before.name === 'Asha');
console.log('no changes gives an empty patch:', diff(after, structuredClone(after)).length);
console.log('type change is a replace:', JSON.stringify(diff({ a: [1] }, { a: { x: 1 } })), '| null vs object:', JSON.stringify(diff({ a: null }, { a: {} })));
console.log('root replace:', JSON.stringify(diff(1, 2)), JSON.stringify(applyPatch(1, [{ op: 'replace', path: '', value: 2 }])));
try { applyPatch({}, [{ op: 'replace', path: '/missing/deep', value: 1 }]); } catch (error) { console.log('bad path:', error.message); }

const front = diff({ list: [1, 2, 3] }, { list: [0, 1, 2, 3] });
console.log('insert at the front with an index diff:', front.length, 'operations');

function mulberry32(seed) {
  return () => {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function randomValue(rand, depth = 0) {
  const kind = Math.floor(rand() * (depth > 2 ? 4 : 6));
  if (kind === 0) return Math.floor(rand() * 5);
  if (kind === 1) return ['x', 'y', 'a/b', 'k~'][Math.floor(rand() * 4)];
  if (kind === 2) return rand() < 0.5 ? null : rand() < 0.5;
  if (kind === 3) return Math.floor(rand() * 3);
  if (kind === 4) return Array.from({ length: Math.floor(rand() * 4) }, () => randomValue(rand, depth + 1));
  const object = {};
  for (let i = Math.floor(rand() * 4); i > 0; i--) object[['a', 'b', 'c/d', 'e~f'][Math.floor(rand() * 4)]] = randomValue(rand, depth + 1);
  return object;
}
function sortKeys(v) {
  if (Array.isArray(v)) return v.map(sortKeys);
  if (isObject(v)) return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
  return v;
}
const rand = mulberry32(2026);
let failures = 0;
const total = 3000;
for (let i = 0; i < total; i++) {
  const a = randomValue(rand);
  const b = randomValue(rand);
  const snapshot = JSON.stringify(a);
  const rebuilt = applyPatch(a, diff(a, b));
  const same = JSON.stringify(sortKeys(rebuilt)) === JSON.stringify(sortKeys(b));
  if (!same || JSON.stringify(a) !== snapshot) failures++;
}
console.log(`random round trips: ${total}, failures: ${failures}`);

Run with Node.js v24.22.1 as js-199.js; two runs gave identical output. Output: replace /name = "Asha K" replace /tags/1 = "z" remove /tags/2 remove /address/zip add /address/country = "IN" replace /a~1b = 2 add /extra = [1] round trip equal: true | input unchanged: true no changes gives an empty patch: 0 type change is a replace: [{"op":"replace","path":"/a","value":{"x":1}}] | null vs object: [{"op":"replace","path":"/a","value":{}}] root replace: [{"op":"replace","path":"","value":2}] 2 bad path: path not found: /missing/deep insert at the front with an index diff: 4 operations random round trips: 3000, failures: 0

Key points

  • Operations add, remove, and replace with JSON Pointer paths; escape ~ and / in keys.
  • Objects: compare keys and recurse; arrays: compare by index, remove from the end.
  • Distinguish arrays, plain objects, and null; clone values into the patch.
  • Apply patches without mutating the input; fail clearly on bad paths.
  • Test the round trip with random data; consider LCS or keys for better array diffs.

Common mistakes

  • Treating null as an object, or arrays like objects.
  • Not escaping slashes and tildes in keys.
  • Removing array items from the start, which shifts the indexes of later removals.
  • Mutating the input or putting references to the source into the patch.

Follow-ups

  • How would you generate move operations for reordered lists?
  • How would you handle patches that conflict with concurrent changes?
  • What does the test operation protect against?

Tips

  • Write the four cases of the algorithm in order.
  • Mention JSON Pointer escaping and removal from the end.
  • Offer the random round-trip test.