Skip to content

Commit 909ee9b

Browse files
authored
sort edits with applyEdits (microsoft#69)
1 parent 33f744b commit 909ee9b

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/main.ts

+17-3
Original file line numberDiff line numberDiff line change
@@ -418,9 +418,23 @@ export function modify(text: string, path: JSONPath, value: any, options: Modifi
418418
* @returns The text with the applied edits.
419419
* @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
420420
*/
421-
export function applyEdits(text: string, edits: EditResult): string {
422-
for (let i = edits.length - 1; i >= 0; i--) {
423-
text = edit.applyEdit(text, edits[i]);
421+
export function applyEdits(text: string, edits: EditResult): string {
422+
let sortedEdits = edits.slice(0).sort((a, b) => {
423+
const diff = a.offset - b.offset;
424+
if (diff === 0) {
425+
return a.length - b.length;
426+
}
427+
return diff;
428+
});
429+
let lastModifiedOffset = text.length;
430+
for (let i = sortedEdits.length - 1; i >= 0; i--) {
431+
let e = sortedEdits[i];
432+
if (e.offset + e.length <= lastModifiedOffset) {
433+
text = edit.applyEdit(text, e);
434+
} else {
435+
throw new Error('Overlapping edit');
436+
}
437+
lastModifiedOffset = e.offset;
424438
}
425439
return text;
426440
}

0 commit comments

Comments
 (0)