Skip to content

Instantly share code, notes, and snippets.

@jclem
Created October 20, 2021 18:35
Show Gist options
  • Save jclem/309cb1dfe843ea6096fd41e0f03b78da to your computer and use it in GitHub Desktop.
Save jclem/309cb1dfe843ea6096fd41e0f03b78da to your computer and use it in GitHub Desktop.
string-scanner.ts
/**
* Scans over a string, character by character
*/
export default class StringScanner {
pos = 0
constructor(private readonly data: string) {}
/**
* Fetch the next character.
*/
next(): string | undefined {
return this.data[this.pos++]
}
/**
* Peek at the next character.
*/
peek(): string | undefined {
return this.data[this.pos + 1]
}
/**
* Rewind the position by 1.
*/
rewind(): void {
const newPos = this.pos - 1
this.pos = newPos < 0 ? 0 : newPos
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment