@@ -22,33 +22,20 @@ import {
2222class Context {
2323 text ;
2424 comments : Comment [ ] = [ ] ;
25- #linesAndColumns: LinesAndColumns ;
25+ #lineCounter: YAML . LineCounter ;
2626
27- constructor ( text : string ) {
27+ constructor ( text : string , lineCounter : YAML . LineCounter ) {
2828 this . text = text ;
29- this . #linesAndColumns = new LinesAndColumns ( text ) ;
30- }
31-
32- #getRangePosition( range : Range ) : { start : Point ; end : Point } {
33- if ( this . text === "" && range . origStart === 0 && range . origEnd === 0 ) {
34- return {
35- start : { offset : 0 , line : 1 , column : 1 } ,
36- end : { offset : 0 , line : 1 , column : 1 } ,
37- } ;
38- }
39-
40- return {
41- start : this . #linesAndColumns. getPoint ( range . origStart ) ,
42- end : this . #linesAndColumns. getPoint ( range . origEnd ) ,
43- } ;
29+ this . #lineCounter = lineCounter ;
4430 }
4531
4632 transformOffset ( offset : number ) : Point {
47- return this . #linesAndColumns. getPoint ( offset ) ;
33+ const { line, col } = this . #lineCounter. linePos ( offset ) ;
34+ return { line, column : col , offset } ;
4835 }
4936
5037 transformRange ( range : Range ) : Position {
51- const { start, end } = this . #getRangePosition ( range ) ;
38+ const [ start , end ] = range . map ( position => this . transformOffset ( position ) ) ;
5239 return createPosition ( start , end ) ;
5340 }
5441
@@ -85,58 +72,3 @@ class Context {
8572}
8673
8774export default Context ;
88-
89- class LinesAndColumns {
90- private lineBreakIndices : number [ ] ;
91-
92- constructor ( text : string ) {
93- this . lineBreakIndices = [ ] ;
94- for ( let i = 0 ; i < text . length ; i ++ ) {
95- const ch = text [ i ] ;
96- if ( ch === "\n" ) {
97- this . lineBreakIndices . push ( i ) ;
98- } else if ( ch === "\r" ) {
99- if ( i + 1 < text . length && text [ i + 1 ] === "\n" ) {
100- this . lineBreakIndices . push ( i + 1 ) ;
101- i ++ ;
102- } else {
103- this . lineBreakIndices . push ( i ) ;
104- }
105- }
106- }
107- }
108-
109- /**
110- * Get line and column for the given offset.
111- * @param offset 0-based offset
112- * @returns 1-based line and 1-based column
113- */
114- getPoint ( offset : number ) : Point {
115- let low = 0 ;
116- let high = this . lineBreakIndices . length - 1 ;
117-
118- while ( low <= high ) {
119- const mid = Math . floor ( ( low + high ) / 2 ) ;
120- const lineBreakIndex = this . lineBreakIndices [ mid ] ;
121-
122- if ( lineBreakIndex < offset ) {
123- low = mid + 1 ;
124- } else if ( lineBreakIndex > offset ) {
125- high = mid - 1 ;
126- } else {
127- return {
128- line : mid + 1 ,
129- column :
130- mid === 0 ? offset + 1 : offset - this . lineBreakIndices [ mid - 1 ] ,
131- offset,
132- } ;
133- }
134- }
135-
136- const line = low + 1 ;
137- const lineStartIndex = low === 0 ? 0 : this . lineBreakIndices [ low - 1 ] + 1 ;
138- const column = offset - lineStartIndex + 1 ;
139-
140- return { line, column, offset } ;
141- }
142- }
0 commit comments