Skip to content

Commit

Permalink
fix: do not store string
Browse files Browse the repository at this point in the history
There's no need to keep a reference to the original string. Doing so just prevents it from being GC'd. This also marks the properties as `readonly` and changes the `SourceLocation` type to be an `interface` instead.
  • Loading branch information
eventualbuddha committed Nov 23, 2021
1 parent 1596423 commit 3ce4df0
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/index.ts
@@ -1,4 +1,4 @@
export type SourceLocation = {
export interface SourceLocation {
line: number
column: number
}
Expand All @@ -7,12 +7,11 @@ const LF = '\n'
const CR = '\r'

export class LinesAndColumns {
private string: string
private offsets: Array<number>
private readonly length: number
private readonly offsets: ReadonlyArray<number>

constructor(string: string) {
this.string = string

this.length = string.length
const offsets = [0]

for (let offset = 0; offset < string.length; ) {
Expand Down Expand Up @@ -40,7 +39,7 @@ export class LinesAndColumns {
}

locationForIndex(index: number): SourceLocation | null {
if (index < 0 || index > this.string.length) {
if (index < 0 || index > this.length) {
return null
}

Expand Down Expand Up @@ -73,7 +72,7 @@ export class LinesAndColumns {
const offset = this.offsets[line]
const nextOffset =
line === this.offsets.length - 1
? this.string.length
? this.length
: this.offsets[line + 1]
return nextOffset - offset
}
Expand Down

0 comments on commit 3ce4df0

Please sign in to comment.