@@ -240,6 +240,33 @@ function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) {
240
240
return false ;
241
241
}
242
242
243
+ /**
244
+ * Performs binary search to find the line number containing a given character index.
245
+ * Returns the lower bound - the index of the first element greater than the target.
246
+ * **Please note that the `lineStartIndices` should be sorted in ascending order**.
247
+ * - Time Complexity: O(log n) - Significantly faster than linear search for large files.
248
+ * @param {number[] } lineStartIndices Sorted array of line start indices.
249
+ * @param {number } target The character index to find the line number for.
250
+ * @returns {number } The 1-based line number for the target index.
251
+ * @private
252
+ */
253
+ function findLineNumberBinarySearch ( lineStartIndices , target ) {
254
+ let low = 0 ;
255
+ let high = lineStartIndices . length ;
256
+
257
+ while ( low < high ) {
258
+ const mid = ( ( low + high ) / 2 ) | 0 ; // Use bitwise OR to floor the division
259
+
260
+ if ( target < lineStartIndices [ mid ] ) {
261
+ high = mid ;
262
+ } else {
263
+ low = mid + 1 ;
264
+ }
265
+ }
266
+
267
+ return low ;
268
+ }
269
+
243
270
//-----------------------------------------------------------------------------
244
271
// Directive Comments
245
272
//-----------------------------------------------------------------------------
@@ -721,9 +748,9 @@ class SourceCode extends TokenStore {
721
748
722
749
/**
723
750
* Converts a source text index into a (line, column) pair.
724
- * @param {number } index The index of a character in a file
751
+ * @param {number } index The index of a character in a file.
725
752
* @throws {TypeError|RangeError } If non-numeric index or index out of range.
726
- * @returns {{line: number, column: number} } A {line, column} location object with a 0-indexed column
753
+ * @returns {{line: number, column: number} } A {line, column} location object with 1-indexed line and 0-indexed column.
727
754
* @public
728
755
*/
729
756
getLocFromIndex ( index ) {
@@ -758,7 +785,7 @@ class SourceCode extends TokenStore {
758
785
const lineNumber =
759
786
index >= this . lineStartIndices . at ( - 1 )
760
787
? this . lineStartIndices . length
761
- : this . lineStartIndices . findIndex ( el => index < el ) ;
788
+ : findLineNumberBinarySearch ( this . lineStartIndices , index ) ;
762
789
763
790
return {
764
791
line : lineNumber ,
0 commit comments