All files / utils/algorithms time.utils.js

100% Statements 40/40
100% Branches 9/9
100% Functions 2/2
100% Lines 40/40

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 411x 1x 1x 1x 1x 1x 4x 1x 1x 3x 3x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 4x 1x 1x 1x 4x 4x 4x 1x  
/**
 * Parses ISO-8601 text to unix timestamp
 * @param {string} text - ISO8601 input as string
 * @returns {number} the representing ISO date as milliseconds from UNIX time on valid input, NaN on invalid input
 */
export function parseISO8601 (text) {
  if (typeof text !== 'string') {
    return NaN
  }
  const iso8601Regex =
    /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d)/
  return !text.match(iso8601Regex) ? NaN : Date.parse(text)
}
 
/**
 * Returns current time and memoizes it for the duration of a frame
 *
 * This function exists because many operations related to relative time
 * relies on current time, calling Date.now() continuously not only returns
 * different result each call, it is expensive. Calling it continuously
 * will affect performance
 *
 * The impact of different results in Date.now() is that each frame you may,
 * see inconsistent results on all ticking elements in a screen (one or two elements jumps 2 seconds,
 * or no seconds at all, while others are ok)
 * @returns {number} the current time, or the time of first call if called more than once during a frame
 */
export const timeNowFrame = (() => {
  /** @type {number | null} */
  let frameTime = null
 
  return function timeNowFrame () {
    if (frameTime === null) {
      frameTime = Date.now()
      requestAnimationFrame(() => { frameTime = null })
    }
 
    return frameTime
  }
})()