json-diff-ts 5.0.0-alpha.8 → 5.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1297,7 +1297,8 @@ function walkChanges(changes, basePath, oldCtx, newCtx, ops, options) {
1297
1297
  const childOld = change.key === "$root" ? oldCtx : oldCtx?.[change.key];
1298
1298
  const childNew = change.key === "$root" ? newCtx : newCtx?.[change.key];
1299
1299
  if (change.embeddedKey) {
1300
- for (const childChange of change.changes) {
1300
+ const orderedChildChanges = orderArrayChildChanges(change.changes, change.embeddedKey);
1301
+ for (const childChange of orderedChildChanges) {
1301
1302
  const filterPath = buildCanonicalFilterPath(
1302
1303
  childPath,
1303
1304
  change.embeddedKey,
@@ -1324,6 +1325,46 @@ function walkChanges(changes, basePath, oldCtx, newCtx, ops, options) {
1324
1325
  }
1325
1326
  }
1326
1327
  }
1328
+ function orderArrayChildChanges(changes, embeddedKey) {
1329
+ if (embeddedKey !== "$index") {
1330
+ return changes;
1331
+ }
1332
+ const groups = [];
1333
+ const pureRemoves = [];
1334
+ for (let i = 0; i < changes.length; i++) {
1335
+ const current = changes[i];
1336
+ const next = changes[i + 1];
1337
+ if (current.type === "REMOVE" /* REMOVE */ && next && next.type === "ADD" /* ADD */ && String(current.key) === String(next.key)) {
1338
+ groups.push({ kind: "preserved", changes: [current, next] });
1339
+ i++;
1340
+ continue;
1341
+ }
1342
+ if (current.type === "REMOVE" /* REMOVE */) {
1343
+ pureRemoves.push(current);
1344
+ groups.push({ kind: "pure-remove" });
1345
+ continue;
1346
+ }
1347
+ groups.push({ kind: "preserved", changes: [current] });
1348
+ }
1349
+ if (pureRemoves.length < 2) {
1350
+ return changes;
1351
+ }
1352
+ const removeIndices = pureRemoves.map((change) => Number(change.key));
1353
+ if (removeIndices.some((idx) => !Number.isInteger(idx))) {
1354
+ return changes;
1355
+ }
1356
+ pureRemoves.sort((a, b) => Number(b.key) - Number(a.key));
1357
+ const ordered = [];
1358
+ let removeIndex = 0;
1359
+ for (const group of groups) {
1360
+ if (group.kind === "pure-remove") {
1361
+ ordered.push(pureRemoves[removeIndex++]);
1362
+ } else {
1363
+ ordered.push(...group.changes);
1364
+ }
1365
+ }
1366
+ return ordered;
1367
+ }
1327
1368
  function emitLeafOp(change, path, ops, options) {
1328
1369
  switch (change.type) {
1329
1370
  case "ADD" /* ADD */: {