Skip to content

Commit

Permalink
perf(manipulation): #807 - Optimise getTextFromTextChanges performance
Browse files Browse the repository at this point in the history
Refs:
- #806
  • Loading branch information
killagu committed Apr 8, 2020
1 parent 29765b5 commit d6f461f
Showing 1 changed file with 13 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@ import { ts } from "@ts-morph/common";
import { SourceFile, TextChange } from "../../compiler";

export function getTextFromTextChanges(sourceFile: SourceFile, textChanges: ReadonlyArray<TextChange | ts.TextChange>) {
// reverse the order
const reversedFormattingEdits = textChanges.map((edit, index) => ({ edit: toWrappedTextChange(edit), index })).sort((a, b) => {
const aStart = a.edit.getSpan().getStart();
const bStart = b.edit.getSpan().getStart();
const difference = bStart - aStart;
if (difference === 0)
return a.index < b.index ? 1 : -1;
return difference > 0 ? 1 : -1;
});

let text = sourceFile.getFullText();
for (const { edit } of reversedFormattingEdits) {
const text = sourceFile.getFullText();
let start = 0;
let end = 0;
const editResult: Array<string> = [];
for (const textChange of textChanges) {
const edit = toWrappedTextChange(textChange);
const span = edit.getSpan();
text = text.slice(0, span.getStart()) + edit.getNewText() + text.slice(span.getEnd());
end = span.getStart();
const beforeEdit = text.slice(start, end);
start = span.getEnd();
editResult.push(beforeEdit);
editResult.push(edit.getNewText());
}
return text;
editResult.push(text.slice(start));
return editResult.join('');

function toWrappedTextChange(change: TextChange | ts.TextChange) {
if (change instanceof TextChange)
Expand Down

0 comments on commit d6f461f

Please sign in to comment.