Skip to content

Commit

Permalink
sort edits with applyEdits (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
aeschli authored Aug 30, 2022
1 parent 33f744b commit 909ee9b
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,9 +418,23 @@ export function modify(text: string, path: JSONPath, value: any, options: Modifi
* @returns The text with the applied edits.
* @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
*/
export function applyEdits(text: string, edits: EditResult): string {
for (let i = edits.length - 1; i >= 0; i--) {
text = edit.applyEdit(text, edits[i]);
export function applyEdits(text: string, edits: EditResult): string {
let sortedEdits = edits.slice(0).sort((a, b) => {
const diff = a.offset - b.offset;
if (diff === 0) {
return a.length - b.length;
}
return diff;
});
let lastModifiedOffset = text.length;
for (let i = sortedEdits.length - 1; i >= 0; i--) {
let e = sortedEdits[i];
if (e.offset + e.length <= lastModifiedOffset) {
text = edit.applyEdit(text, e);
} else {
throw new Error('Overlapping edit');
}
lastModifiedOffset = e.offset;
}
return text;
}

0 comments on commit 909ee9b

Please sign in to comment.