Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

offset-to-loc.ts

39 lines950 Bytes

1export interface Loc {
2 /** 1-based line number */
3 line: number
4 /** 0-based column offset */
5 column: number
6}
7​
8/**
9 * Pre-compute line start offsets for fast byte-offset to line/column conversion.
10 * Returns a function that maps a byte offset to `{ line, column }`.
11 *
12 * Build: O(n) single pass over the source string.
13 * Lookup: O(log n) binary search.
14 */
15export function createLocMapper(source: string): (offset: number) => Loc {
16 const lineStarts: Array<number> = [0]
17 for (let i = 0; i < source.length; i++) {
18 if (source.charCodeAt(i) === 10 /* \n */) {
19 lineStarts.push(i + 1)
20 }
21 }
22​
23 return (offset: number): Loc => {
24 let lo = 0
25 let hi = lineStarts.length - 1
26 while (lo < hi) {
27 const mid = (lo + hi + 1) >> 1
28 if (lineStarts[mid]! <= offset) {
29 lo = mid
30 } else {
31 hi = mid - 1
32 }
33 }
34 return {
35 line: lo + 1,
36 column: offset - lineStarts[lo]!,
37 }
38 }