# All files / utils formatters.ts

89.28% Statements 100/112
80.48% Branches 66/82
94.11% Functions 16/17
89.52% Lines 94/105

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
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349

    3x
    3x

    3x

    3x

    3x
    3x
    3x
    3x

    3x

    3x
    17x

    17x

    33x
    33x
    33x
    33x
    33x

    33x

    33x

    33x

    4x
    4x
    4x

    32x
    32x

    32x

    32x
    11x
    4x

    7x
    5x

    2x

    21x
    21x
    21x

    4x
    2x
    10x
    10x

    10x

    17x

    33x
    37x
    37x

    33x

    28x
    31x

    12x
    6x

    6x
    3x
    11x

    6x

    5x
    1x
    1x

    6x

    33x
    33x

    3x

    3x

    8x
    16x
    16x
    16x
    16x
    16x

    8x

    8x
    12x
    12x
    12x
    12x

    12x

    12x

    12x

    8x

    8x

    3x

    6x
    12x
    12x
    12x
    12x
    12x

    6x

    6x

    6x

    9x
    2x

    2x

    7x

    6x

    6x

     /*
      This module contains utilites for formatting values in visualizations.

      A `Formatter` takes a value in a table and formats it as a user-facing
      string. A formatter factory creates a `Formatter`. Here we define several
      formatter factories for common use cases such as formatting time values, or
      formatting quantities of bytes.

          // Create a formatter by calling the factory
          const myTimeFormatter = timeFormatter({timezone: 'America/New_York'})

          // Use the formatter to get a user-friendly string representation of a value
          myTimeFormatter(1562018849599)

          // => returns "1 July 2019"

    */

    import {format as d3Format} from 'd3-format'
    import {createDateFormatter} from 'intl-dateformat'

    import {Formatter, FormatterType} from '../types'

    const DEFAULT_TIME_FORMATS = {
      local12: 'YYYY-MM-DD hh:mm:ss A',
      local24: 'YYYY-MM-DD HH:mm:ss ZZ',
      zoned12: 'YYYY-MM-DD hh:mm:ss A ZZ',
      zoned24: 'YYYY-MM-DD HH:mm:ss ZZ',
    }

    const MINUTE = 1000 * 60
    const HOUR = 1000 * 60 * 60
    const DAY = 1000 * 60 * 60 * 24
    const WEEK = 1000 * 60 * 60 * 24 * 7

    const TIME_FORMATS_BY_GRANULARITY = [
      {
        minWidth: 0,
        maxWidth: 1 * MINUTE,
        local12: 'hh:mm:ss.sss A',
        local24: 'HH:mm:ss.sss ZZ',
        zoned12: 'hh:mm:ss.sss A ZZ',
        zoned24: 'HH:mm:ss.sss ZZ',
      },
      {
        minWidth: 1 * MINUTE,
        maxWidth: 1 * HOUR,
        local12: 'hh:mm:ss A',
        local24: 'HH:mm:ss ZZ',
        zoned12: 'hh:mm:ss A ZZ',
        zoned24: 'HH:mm:ss ZZ',
      },
      {
        minWidth: 1 * HOUR,
        maxWidth: 1 * DAY,
        local12: 'hh:mm A',
        local24: 'HH:mm ZZ',
        zoned12: 'hh:mm A ZZ',
        zoned24: 'HH:mm ZZ',
      },
      {
        minWidth: 1 * DAY,
        maxWidth: 2 * WEEK,
        local12: 'MMM DD, hh:mm A',
        local24: 'MMM DD, HH:mm ZZ',
        zoned12: 'MMM DD, hh:mm A ZZ',
        zoned24: 'MMM DD, HH:mm ZZ',
      },
      {
        minWidth: 2 * WEEK,
        maxWidth: 4 * WEEK,
        local12: 'MMM DD',
        local24: 'MMM DD',
        zoned12: 'MMM DD',
        zoned24: 'MMM DD',
      },
      {
        minWidth: 4 * WEEK,
        maxWidth: Infinity,
        local12: 'YYYY-MM-DD',
        local24: 'YYYY-MM-DD',
        zoned12: 'YYYY-MM-DD',
        zoned24: 'YYYY-MM-DD',
      },
    ]

    // Get the "short" name for a time zone, e.g. "America/Los_Angeles" => PST
    const getShortTimeZoneName = (timeZone: string, date: Date) => {
      const formatted = new Intl.DateTimeFormat('en-US', {
        timeZone,
        year: 'numeric',
        month: 'numeric',
        timeZoneName: 'short',
      }).format(date)

      return formatted.substring(formatted.indexOf(',') + 2)
    }

    interface TimeFormatter extends Formatter {
      (timestamp: number, options?: {domainWidth?: number}): string

      _GIRAFFE_FORMATTER_TYPE: FormatterType.Time
    }

    export interface TimeFormatterFactoryOptions {
      // BCP 47 language tag or "default"
      locale?: string

      // IANA Time Zone Database name (e.g. "America/New_York") or "UTC"
      timeZone?: string

      // Whether to use a 12- or 24-hour clock (default true)
      hour12?: boolean

      // Format string, e.g. "YYYY-MM-DD HH:mm".
      //
      // Support options are those [here][0], as well as:
      //
      // - `sss`: milliseconds
      // - `Z`: short time zone name (e.g. "PST")
      // - `D`: day of month without zero padding
      //
      // [0]: https://github.com/zapier/intl-dateformat#formats
      format?: string
    }

    export const timeFormatter = ({
      locale,
      timeZone,
      format,
      hour12,
    }: TimeFormatterFactoryOptions = {}): TimeFormatter => {
      // RegEx to check for "UTC" case insensitive
      const UTC_TIME_ZONE = /utc/i

      // this check is used to determine whether a user's locale is 24h or 12h
      const is24hourLocale = new Date(2014, 1, 1, 15, 0, 0, 0)
        .toLocaleTimeString()
        .includes('15')

      // createDateFormatter is very particular in terms of order of operation
      // for example, modifying the timezone before determing the `am/pm` will
      // output the timezone incorrectly. The same goes for determining the `HH`, etc...
      const formatStringFormatter = createDateFormatter({
        // a deliberate space in front of single digit hours keeps the tick label length
        // and the total number of ticks consistent regardless of time frame
        hh: options => {
          const {hour} = options
          const numericalHour = Number(hour)
          return numericalHour < 10 ? ` ${numericalHour}` : `${numericalHour}`
        },
        HH: options => {
          const {hour, lhour} = options
          const hasMeridiem = / a/i
          const is24hourFormat =
            is24hourLocale || UTC_TIME_ZONE.test(timeZone) || hour12 === false

          if (hasMeridiem.test(format)) {
            if (Number(lhour) === 0) {
              return '12'
            }
            if (Number(lhour) > 12) {
              return String(Number(lhour) - 12)
            }
            return String(Number(lhour))
          }
          if (is24hourFormat) {
            const numericalHour = Number(lhour) % 24
            return numericalHour < 10 ? `0${numericalHour}` : `${numericalHour}`
          }
          return hour
        },
        sss: (_, date) => String(date.getMilliseconds()).padStart(3, '0'),
        D: parts => String(Number(parts.day)),
        a: ({dayPeriod, lhour}) => {
          Iif (format && format.includes('a') && is24hourLocale) {
            if (Number(lhour) >= 12) {
              return 'PM'
            } else {
              return 'AM'
            }
          }
          return dayPeriod || ''
        },
        ZZ: (_, date) => getShortTimeZoneName(timeZone, date),
      })

      let formatter

      const getValidDate = (timestamp: number): Date => {
        const date = new Date(timestamp)
        return date.getTime() === date.getTime() ? date : new Date()
      }

      if (format) {
        // If a `format` string is passed, we simply use it
        formatter = (timestamp: number) =>
          formatStringFormatter(getValidDate(timestamp), format, {
            locale,
            timezone: timeZone,
          })
      } else {
        // Otherwise we will return a formatter that will vary the output format
        // based on an optional `domainWidth` argument (e.g. we will show more
        // detail in a formatted timestamp if a user is viewing data in a short
        // time range)
        formatter = (timestamp: number, {domainWidth = null} = {}) => {
          let timeFormats = DEFAULT_TIME_FORMATS

          if (domainWidth) {
            timeFormats = TIME_FORMATS_BY_GRANULARITY.find(
              d => d.minWidth <= domainWidth && d.maxWidth > domainWidth
            )
          }

          let timeFormat

          if (
            (timeZone === 'UTC' && hour12 === undefined) ||
            (timeZone && hour12 === false)
          ) {
            timeFormat = timeFormats.zoned24
          } else if (timeZone) {
            timeFormat = timeFormats.zoned12
          } else Eif (hour12 === false) {
            timeFormat = timeFormats.local24
          } else if (is24hourLocale) {
            // this implementation checks the user's OS/browser settings to
            // check whether their locale is 12h or 24h
            // Evaluating true means that the local is based on a 24h locale
            timeFormat = timeFormats.local24
          } else {
            timeFormat = timeFormats.local12
          }

          return formatStringFormatter(getValidDate(timestamp), timeFormat, {
            timezone: timeZone,
            locale,
          })
        }
      }

      formatter._GIRAFFE_FORMATTER_TYPE = FormatterType.Time
      return formatter
    }

    export const BINARY_PREFIX_FORMATTER_TYPE: 'BINARY_PREFIX' = 'BINARY_PREFIX'

    const BINARY_PREFIXES = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']

    interface BinaryPrefixFormatter extends Formatter {
      (x: number): string

      _GIRAFFE_FORMATTER_TYPE: FormatterType.BinaryPrefix
    }

    interface BinaryPrefixFormatterFactoryOptions {
      prefix?: string
      suffix?: string
      significantDigits?: number
      trimZeros?: boolean
      format?: boolean
    }

    export const binaryPrefixFormatter = ({
      prefix = '',
      suffix = '',
      significantDigits = 6,
      trimZeros = true,
      format = true,
    }: BinaryPrefixFormatterFactoryOptions = {}): BinaryPrefixFormatter => {
      const formatSigFigs = d3Format(
        `.${significantDigits}${trimZeros ? '~' : ''}f`
      )

      const formatter = (x: number) => {
        const isXBig = Math.abs(x) >= 1024
        const i = Math.floor(Math.log(Math.abs(x)) / Math.log(2 ** 10))
        const binaryFormattedNumber = isXBig ? x / 1024 ** i : x
        const binaryPrefix = isXBig ? ' ' + BINARY_PREFIXES[i] : ''

        const decimalFormattedNumber = formatSigFigs(binaryFormattedNumber)

        Iif (format !== true) {
          return `${prefix}${x}${suffix}`
        }

        return `${prefix}${decimalFormattedNumber}${binaryPrefix}${suffix}`
      }

      formatter._GIRAFFE_FORMATTER_TYPE = FormatterType.BinaryPrefix as FormatterType.BinaryPrefix

      return formatter
    }

    export const SI_PREFIX_FORMATTER_TYPE: 'SI_PREFIX' = 'SI_PREFIX'

    interface SIPrefixFormatter extends Formatter {
      (x: number): string

      _GIRAFFE_FORMATTER_TYPE: FormatterType.SIPrefix
    }

    interface SIPrefixFormatterFactoryOptions {
      prefix?: string
      suffix?: string
      significantDigits?: number
      trimZeros?: boolean
      format?: boolean
    }

    export const siPrefixFormatter = ({
      prefix = '',
      suffix = '',
      significantDigits = 6,
      trimZeros = true,
      format = true,
    }: SIPrefixFormatterFactoryOptions = {}): SIPrefixFormatter => {
      let formatter
      const formatSIPrefix = d3Format(
        `.${significantDigits}${trimZeros ? '~' : ''}s`
      )

      Iif (format !== true) {
        formatter = (x: number): string => `${prefix}${x}${suffix}`
      } else {
        formatter = (x: number): string => {
          // code below shortens extremely large or small numbers (greater than septillion+) by
          // first converting number to SI format, then removing the SI unit to convert
          // number to scientific notation, and finally
          // adding yotta (Y) back
          if (x >= 1e30 || x <= -1e30) {
            const siFormattedValue = String(formatSIPrefix(Math.abs(x))).slice(
              0,
              -1
            )
            return `${prefix}${x < 0 ? '-' : ''}${d3Format(`.${significantDigits}`)(
              Number(siFormattedValue)
            )}Y${suffix}`
          }
          return `${prefix}${formatSIPrefix(x)}${suffix}`
        }
      }

      formatter._GIRAFFE_FORMATTER_TYPE = FormatterType.SIPrefix as FormatterType.SIPrefix

      return formatter
    }