All files / key-parser expression-formatters.js

73.87% Statements 229/310
78.57% Branches 11/14
23.52% Functions 4/17
73.87% Lines 229/310

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 3111x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 12x 12x       12x 12x 1x 1x 1x 1x 1x 12x 12x       12x 12x 1x 1x 1x 1x 1x 12x 12x       12x 12x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 12x 12x 2x 2x 2x 2x 12x 12x 2x 12x 12x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x     1x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x 1x 1x                                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { isNumeric } from '../utils/algorithms/number.utils.js'
import { parseISO8601, timeNowFrame } from '../utils/algorithms/time.utils.js'
import { getDurationBetweenTimestamps } from '../utils/algorithms/duration.js'
 
/** @type {FormatCall} */
const formatAsIs = (text) => text
 
/** @type {Record<string, Formatter>} */
const baseFormatter = {
  'as is': {
    format: formatAsIs,
  },
 
  number: {
    format: (text, locale) => Intl.NumberFormat(locale.baseName).format(Number(text)),
  },
 
  date: {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return Intl.DateTimeFormat(locale.baseName, defaultDateFormatOptions).format(date)
    },
  },
 
  datetime: {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return Intl.DateTimeFormat(locale.baseName, defaultDateTimeFormatOptions).format(date)
    },
  },
 
  timestamp: {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date(+text) : parseISO8601(text)
      return Intl.DateTimeFormat(locale.baseName, timestampFormatOptions).format(date)
    },
  },
 
  'long date': {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return Intl.DateTimeFormat(locale.baseName, longDateFormatOptions).format(date)
    },
  },
 
  'long datetime': {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return Intl.DateTimeFormat(locale.baseName, longDateTimeFormatOptions).format(date)
    },
  },
}
 
/** @satisfies {[Intl.RelativeTimeFormatUnit, number][]} */
const durationUnitsEntries = [
  ['year', 1000 * 60 * 60 * 24 * 365],
  ['month', 1000 * 60 * 60 * 24 * 365 / 12],
  ['day', 1000 * 60 * 60 * 24],
  ['hour', 1000 * 60 * 60],
  ['minute', 1000 * 60],
  ['second', 1000],
]
 
export const durationUnits = Object.freeze(/** @type {const} */(['years', 'months', 'days', 'hours', 'minutes', 'seconds']))
 
/** @type {Record<string, Formatter>} */
const baseRelativeTimeFormatter = {
  'relative time': {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return relativeTimeFormat(locale, date.valueOf())
    },
  },
}
 
/** @type {Record<string, Formatter>} */
const relativeTimeDurationFormatter = {
  'relative time duration': {
    format: (text, locale) => {
      const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
      return relativeTimeDurationFormat(locale, date.valueOf())
    },
  },
}
 
/** @type {Record<string, Formatter>} */
const baseInUnitRelativeTimeFormatter = Object.fromEntries(
  durationUnitsEntries.map(([unit]) => {
    return [`in ${unit}s`, {
      format: (text, locale) => {
        const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
        return relativeTimeFormatInUnit(locale, unit, date.valueOf())
      },
    }]
  })
)
 
/** @type {Record<string, Formatter>} */
const baseDurationInUnitRelativeTimeFormatter = Object.fromEntries(
  durationUnitsEntries.map(([unit]) => {
    return [`in ${unit}s`, {
      format: (text, locale) => {
        const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
        return relativeTimeDurationFormatInUnit(locale, unit, date.valueOf())
      },
    }]
  })
)
 
/** @type {Record<string, Formatter>} */
const baseToUnitRelativeTimeFormatter = Object.fromEntries(
  durationUnitsEntries.map(([unit, duration]) => {
    return [`to ${unit}s`, {
      format: (text, locale) => {
        const date = isNumeric(text) ? new Date((+text) * 1000) : parseISO8601(text)
        return relativeTimeFormatToUnit(locale, unit, date.valueOf())
      },
    }]
  })
)
 
const relativeTimeFormatters = (() => {
  const result = {
    ...baseRelativeTimeFormatter,
    ...relativeTimeDurationFormatter,
  }
 
  for (const [baseKey] of Object.entries(baseRelativeTimeFormatter)) {
    for (const [unitPostfix, unitParams] of Object.entries(baseInUnitRelativeTimeFormatter)) {
      result[`${baseKey} ${unitPostfix}`] = unitParams
    }
  }
 
  for (const [baseKey] of Object.entries(relativeTimeDurationFormatter)) {
    for (const [unitPostfix, unitParams] of Object.entries(baseDurationInUnitRelativeTimeFormatter)) {
      result[`${baseKey} ${unitPostfix}`] = unitParams
    }
    for (const [unitPostfix, unitParams] of Object.entries(baseToUnitRelativeTimeFormatter)) {
      result[`${baseKey} ${unitPostfix}`] = unitParams
    }
  }
 
  return result
})()
 
/** @type {Intl.DateTimeFormatOptions} */
const defaultDateTimeFormatOptions = {
  dateStyle: 'short',
  timeStyle: 'medium',
}
 
/** @type {Intl.DateTimeFormatOptions} */
const defaultDateFormatOptions = {
  dateStyle: 'short',
}
 
/** @type {Intl.DateTimeFormatOptions} */
const timestampFormatOptions = {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  fractionalSecondDigits: 3,
  hour12: false,
}
 
/** @type {Intl.DateTimeFormatOptions} */
const longDateFormatOptions = {
  dateStyle: 'long',
}
 
/** @type {Intl.DateTimeFormatOptions} */
const longDateTimeFormatOptions = {
  dateStyle: 'long',
  timeStyle: 'long',
}
 
/**
 * Shows relative time based on locale
 * @param {Intl.Locale} locale - target locale
 * @param {number} d1 target timestamp
 * @param {number} d2 timestamp to compare, if not defined uses current time
 * @returns {string} formatted relative time
 */
function relativeTimeFormat (locale, d1, d2 = timeNowFrame()) {
  const formatter = new Intl.RelativeTimeFormat(locale.baseName, { numeric: 'auto' })
  const duration = getDurationBetweenTimestamps(d1, d2)
  for (const unit of durationUnits) {
    if (duration[unit] > 0) {
      return formatter.format(duration[unit] * Math.sign(d1 - d2), unit)
    }
  }
  return formatter.format(0, 'seconds')
}
 
/**
 * Shows relative time based on locale, without any time adverbs such as "ago" (2 minutes ago), "in" (in 5 minutes), tomorrow, yesterday, etc
 * @param {Intl.Locale} locale - target locale
 * @param {number} d1 - target timestamp
 * @param {number} d2 - timestamp to compare, if not defined uses current time
 * @returns {string} formatted relative time
 */
function relativeTimeDurationFormat (locale, d1, d2 = timeNowFrame()) {
  const duration = getDurationBetweenTimestamps(d1, d2)
  for (const unit of durationUnits) {
    if (duration[unit] > 0) {
      return Intl.NumberFormat(locale.baseName, { style: 'unit', unit, unitDisplay: 'long' }).format(duration[unit])
    }
  }
  return Intl.NumberFormat(locale.baseName, { style: 'unit', unit: 'seconds', unitDisplay: 'long' }).format(0)
}
 
/**
 * Shows relative time based on locale in units
 * @param {Intl.Locale} locale - target locale
 * @param {Intl.RelativeTimeFormatUnit} unit - unit to use on the calc
 * @param {number} d1 - target timestamp
 * @param {number} d2 - timestamp to compare, if not defined uses current time
 * @returns {string} formatted relative time
 */
function relativeTimeFormatInUnit (locale, unit, d1, d2 = timeNowFrame()) {
  const elapsed = d1 - d2
  const formatter = new Intl.RelativeTimeFormat(locale.baseName, { numeric: 'auto' })

  for (const [durationUnit, duration] of durationUnitsEntries) {
    // "Math.abs" accounts for both "past" & "future" scenarios
    if (durationUnit === unit) {
      return formatter.format(Math.floor(elapsed / duration), unit)
    }
  }
  return relativeTimeFormat(locale, d1, d2)
}
 
/**
 * Shows relative time based on locale in units, without any time adverbs such as "ago" (2 minutes ago), "in" (in 5 minutes), tomorrow, yesterday, etc...
 *
 * When the unit is zero it applies the value in the next unit where the value is above zero (0)
 * @param {Intl.Locale} locale - target locale
 * @param {Intl.RelativeTimeFormatUnit} unit unit to use on the calc
 * @param {number} d1 - target timestamp
 * @param {number} d2 - timestamp to compare, if not defined uses current time
 * @returns {string} formatted relative time
 */
function relativeTimeDurationFormatInUnit (locale, unit, d1, d2 = timeNowFrame()) {
  // "Math.abs" accounts for both "past" & "future" scenarios
  const elapsed = Math.abs(d1 - d2)

  for (const [durationUnit, duration] of durationUnitsEntries) {
    if (durationUnit === unit) {
      if (elapsed < duration) { break }
      return Intl.NumberFormat(locale.baseName, { style: 'unit', unit, unitDisplay: 'long' }).format(Math.floor(elapsed / duration))
    }
  }
  return relativeTimeDurationFormat(locale, d1, d2)
}
 
/**
 * Shows relative time based on locale, from the longest unit that has a positive value to the selected unit, without any time adverbs such as "ago" (2 minutes ago), "in" (in 5 minutes), tomorrow, yesterday, etc
 * @param {Intl.Locale} locale - target locale
 * @param {Intl.RelativeTimeFormatUnit} toUnit unit to use on the calc
 * @param {number} d1 - target timestamp
 * @param {number} d2 - timestamp to compare, if not defined uses current time
 * @returns {string} formatted relative time
 */
function relativeTimeFormatToUnit (locale, toUnit, d1, d2 = timeNowFrame()) {
  // "Math.abs" accounts for both "past" & "future" scenarios
  let elapsed = Math.abs(d1 - d2)
  const listFormatter = new Intl.ListFormat(locale.baseName, { style: 'long', type: 'conjunction' })
  const list = []

  for (const [unit, duration] of durationUnitsEntries) {
    if (elapsed > duration) {
      const amount = Math.floor(elapsed / duration)
      const timeUnitFormatter = Intl.NumberFormat(locale.baseName, { style: 'unit', unit, unitDisplay: 'long' })
      list.push(timeUnitFormatter.format(amount))
      elapsed -= amount * duration
    }
    if (unit === toUnit) {
      if (list.length) {
        break
      }
      return relativeTimeDurationFormat(locale, d1, d2)
    }
  }
  return listFormatter.format(list)
}
 
/**
 * @typedef {Record<string, Formatter>} FormatterMap
 */
 
/**
 * @callback FormatCall
 * @param {string}       text   - text input
 * @param {Intl.Locale}  locale - internationalization locale
 * @returns {string}     formatted text
 */
 
/**
 * @typedef {object} Formatter
 * @property {FormatCall} format   - format function
 * @property {boolean} [isConstant] - flag to tell if format function returns the same result given the same input
 */
 
export const formatters = {
  ...baseFormatter,
  ...relativeTimeFormatters,
}