JSFiddle - React, Tailwind, and code Playground

by Renoir Boulanger

TypeScript

class ResponseTime {
  static FALLBACK: TimeResolution = 'nanoseconds'

  abbr: string = ''
  private begin: HighResolutionTimeTuple
  private delta: HighResolutionTimeTuple = [0, 0]

  constructor(public resolution: TimeResolution = 'nanoseconds') {
    this.begin = process.hrtime()
    this.setResolution(resolution)
  }

  setResolution(resolution: TimeResolution = 'nanoseconds') {
    const resolutions = {
      nanoseconds: 'ns',
      milliseconds: 'ms',
      seconds: 's',
    }

    const isValidResolution = Object.keys(resolutions).includes(resolution)
    const res = isValidResolution ? resolution : ResponseTime.FALLBACK

    this.resolution = res
    this.abbr = resolutions[res]
  }

  mark() {
    if (this.delta[1] === 0) {
      this.delta = process.hrtime(this.begin)
    }
  }

  getTime(): number {
    this.mark()
    const nanoseconds: number = this.delta[0] * 1e9 + this.delta[1]
    const milliseconds: number = nanoseconds / 1e6
    const seconds: number = nanoseconds / 1e9

    const available = {
      nanoseconds,
      milliseconds,
      seconds,
    }

    return available[this.resolution] || milliseconds
  }

  toString(): string {
    const abbr = this.abbr
    const time = this.getTime()

    return `${time} ${abbr}`
  }

}