Skip to content

Commit f9c777d

Browse files
committed
Add bulk edit application helper
1 parent ebe11b2 commit f9c777d

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

internal/format/api_test.go

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package format_test
33
import (
44
"os"
55
"path/filepath"
6+
"strings"
67
"testing"
78

89
"github.com/microsoft/typescript-go/internal/ast"
@@ -15,6 +16,24 @@ import (
1516
"gotest.tools/v3/assert"
1617
)
1718

19+
func applyBulkEdits(text string, edits []core.TextChange) string {
20+
b := strings.Builder{}
21+
b.Grow(len(text))
22+
lastEnd := 0
23+
for _, e := range edits {
24+
start := e.TextRange.Pos()
25+
if start != lastEnd {
26+
b.WriteString(text[lastEnd:e.TextRange.Pos()])
27+
}
28+
b.WriteString(e.NewText)
29+
30+
lastEnd = e.TextRange.End()
31+
}
32+
b.WriteString(text[lastEnd:])
33+
34+
return b.String()
35+
}
36+
1837
func TestFormat(t *testing.T) {
1938
t.Parallel()
2039

@@ -46,11 +65,7 @@ func TestFormat(t *testing.T) {
4665
)
4766
ast.SetParentInChildren(sourceFile.AsNode())
4867
edits := format.FormatDocument(ctx, sourceFile)
49-
newText := text
50-
for i := len(edits) - 1; i >= 0; i-- { // iterate edits back to front so no spans need to be adjusted
51-
e := edits[i]
52-
newText = e.ApplyTo(newText)
53-
}
68+
newText := applyBulkEdits(text, edits)
5469
assert.Assert(t, len(newText) > 0)
5570
assert.Assert(t, text != newText)
5671
})
@@ -86,11 +101,7 @@ func BenchmarkFormat(b *testing.B) {
86101
b.Run("format checker.ts", func(b *testing.B) {
87102
for b.Loop() {
88103
edits := format.FormatDocument(ctx, sourceFile)
89-
newText := text
90-
for i := len(edits) - 1; i >= 0; i-- { // iterate edits back to front so no spans need to be adjusted
91-
e := edits[i]
92-
newText = e.ApplyTo(newText)
93-
}
104+
newText := applyBulkEdits(text, edits)
94105
assert.Assert(b, len(newText) > 0)
95106
}
96107
})

0 commit comments

Comments
 (0)