All files / json-path Value.ts

100% Statements 24/24
100% Branches 2/2
100% Functions 4/4
100% Lines 22/22

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    1x   897x 897x 897x       1x 1x 1x 5x 5x   1x 1x       5x 5x 4x 3x 3x       1x 1x 1x 4x 4x   1x      
import type {NormalizedPath} from './types';
 
export class Value {
  constructor(
    public readonly parent: Value | null,
    public readonly step: string | number,
    public readonly data: unknown,
  ) {}
 
  public path(): NormalizedPath {
    const segments: (string | number)[] = [];
    let current: Value | null = this;
    while (current) {
      segments.push(current.step);
      current = current.parent;
    }
    segments.reverse();
    return segments;
  }
 
  public segment(): string {
    const step = this.step;
    if (typeof step === 'number') return '[' + step + ']';
    if (!this.parent) return '$';
    const json = JSON.stringify(step);
    return "['" + json.slice(1, -1) + "']";
  }
 
  public pointer(): string {
    let str = this.segment();
    let current: Value | null = this.parent;
    while (current) {
      str = current.segment() + str;
      current = current.parent;
    }
    return str;
  }
}