All files / json-path Parser.ts

95.45% Statements 21/22
80% Branches 12/15
100% Functions 8/8
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58        4x         186x 186x       186x 186x       5945x       58x 58x 58x       7693x 7693x 7689x                   3343x 3343x 3319x 3319x       3798x       3971x 194x        
/**
 * Basic parser utility class for managing input string and position
 * in the parsing process.
 */
export class Parser {
  public str: string;
  public pos: number;
 
  constructor() {
    this.str = '';
    this.pos = 0;
  }
 
  public reset(input: string): void {
    this.str = input;
    this.pos = 0;
  }
 
  public eof(): boolean {
    return this.pos >= this.str.length;
  }
 
  public peek(len: number = 1): string {
    const {str, pos} = this;
    Iif (pos >= str.length) return '';
    return (len === 1 ? str[pos] : str.slice(pos, pos + len)) || '';
  }
 
  public is(expected: string): boolean {
    const {str, pos} = this;
    if (pos >= str.length) return false;
    return str.slice(pos).startsWith(expected);
  }
 
  /**
   * Match the current position against a regular expression.
   *
   * @param reg - Regular expression to match against the current position.
   * @returns The length of the match if successful, otherwise 0.
   */
  public match(reg: RegExp): number {
    const {str, pos} = this;
    if (pos >= str.length) return 0;
    const m = str.slice(pos).match(reg);
    return m && m.index === 0 && m[0] ? m[0].length : 0;
  }
 
  public skip(count: number): void {
    this.pos += count;
  }
 
  public ws(): void {
    while (!this.eof() && /\s/.test(this.str[this.pos])) {
      this.pos++;
    }
  }
}