File tree Expand file tree Collapse file tree 2 files changed +15
-18
lines changed
Expand file tree Collapse file tree 2 files changed +15
-18
lines changed Original file line number Diff line number Diff line change 1- // Prevent `String#lastIndexOf` treat negative index as `0`
2- const safeLastIndexOf = ( string , searchString , index ) =>
3- index < 0 ? - 1 : string . lastIndexOf ( searchString , index ) ;
4-
1+ // Performance https://github.com/sindresorhus/index-to-position/pull/9
52function getPosition ( text , textIndex ) {
6- const lineBreakBefore = safeLastIndexOf ( text , '\n' , textIndex - 1 ) ;
7- const column = textIndex - lineBreakBefore - 1 ;
8-
9- let line = 0 ;
10- for (
11- let index = lineBreakBefore ;
12- index >= 0 ;
13- index = safeLastIndexOf ( text , '\n' , index - 1 )
14- ) {
15- line ++ ;
16- }
17-
18- return { line, column} ;
3+ const lineBreakBefore = textIndex === 0 ? - 1 : text . lastIndexOf ( '\n' , textIndex - 1 ) ;
4+ return {
5+ line : lineBreakBefore === - 1 ? 0 : text . slice ( 0 , lineBreakBefore + 1 ) . match ( / \n / g) . length ,
6+ column : textIndex - lineBreakBefore - 1 ,
7+ } ;
198}
209
21- export default function indexToLineColumn ( text , textIndex , { oneBased = false } = { } ) {
10+ export default function indexToPosition ( text , textIndex , { oneBased = false } = { } ) {
2211 if ( typeof text !== 'string' ) {
2312 throw new TypeError ( 'Text parameter should be a string' ) ;
2413 }
Original file line number Diff line number Diff line change @@ -72,6 +72,14 @@ test('index on line break', t => {
7272 t . deepEqual ( indexToPosition ( text , 4 ) , { line : 2 , column : 0 } ) ;
7373 }
7474
75+ {
76+ const text = '\n\na' ;
77+ t . deepEqual ( indexToPosition ( text , 0 ) , { line : 0 , column : 0 } ) ;
78+ t . deepEqual ( indexToPosition ( text , 1 ) , { line : 1 , column : 0 } ) ;
79+ t . deepEqual ( indexToPosition ( text , 2 ) , { line : 2 , column : 0 } ) ;
80+ t . deepEqual ( indexToPosition ( text , 3 ) , { line : 2 , column : 1 } ) ;
81+ }
82+
7583 {
7684 const text = '\r\na\r\nb' ;
7785 t . deepEqual ( indexToPosition ( text , 0 ) , { line : 0 , column : 0 } ) ;
You can’t perform that action at this time.
0 commit comments