All files / fmt / duration.ts

100.00% Branches 27/27
100.00% Functions 4/4
100.00% Lines 82/82
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x35
x35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
x3
x3
x3
x3
x3
x3
 
x3
x3
x3
x3
x3
x3
x3
x3
x3
 
 
x3
x16
x16
x16
x16
 
 
x3
x3
 
 
x19
x19
x19
x19
x19
x19
x19
x19
x19
x19
x19
x19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
 
x19
x19
x19
x19
 
x19
 
x19
x19
x9
x9
x9
x9
x9
x9
x19
x4
x4
x4
x4
x4
x4
x19
x5
x35
x5
x5
 
x5
x1
x1
x3
x1
x3
x1
x5
x5
x19
x1
x1
x19
x19












































































































































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Format milliseconds to time duration.
 *
 * ```ts
 * import { format } from "@std/fmt/duration";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(format(99674, { style: "digital" }), "00:00:01:39:674:000:000");
 *
 * assertEquals(format(99674), "0d 0h 1m 39s 674ms 0µs 0ns");
 *
 * assertEquals(format(99674, { ignoreZero: true }), "1m 39s 674ms");
 *
 * assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minute, 39 seconds, 674 milliseconds");
 * ```
 * @module
 */

function addZero(num: number, digits: number) {
  return String(num).padStart(digits, "0");
}

type DurationPartUnit =
  | "days"
  | "hours"
  | "minutes"
  | "seconds"
  | "milliseconds"
  | "microseconds"
  | "nanoseconds";

interface DurationPart {
  unit: DurationPartUnit;
  value: number;
}

const NARROW_UNIT_NAME_MAP = new Map<DurationPartUnit, string>([
  ["days", "d"],
  ["hours", "h"],
  ["minutes", "m"],
  ["seconds", "s"],
  ["milliseconds", "ms"],
  ["microseconds", "µs"],
  ["nanoseconds", "ns"],
]);

const FULL_UNIT_NAME_MAP = new Map<DurationPartUnit, string>([
  ["days", "day"],
  ["hours", "hour"],
  ["minutes", "minute"],
  ["seconds", "second"],
  ["milliseconds", "millisecond"],
  ["microseconds", "microsecond"],
  ["nanoseconds", "nanosecond"],
]);

/** Get key with pluralization */
function getPluralizedKey(unit: DurationPartUnit, value: number) {
  return value === 1
    ? FULL_UNIT_NAME_MAP.get(unit)
    : `${FULL_UNIT_NAME_MAP.get(unit)}s`;
}

/** Parse milliseconds into a duration. */
function millisecondsToDurationParts(
  ms: number,
): DurationPart[] {
  // Duration cannot be negative
  const millis = Math.abs(ms);
  const millisFraction = millis.toFixed(7).slice(-7, -1);
  return [
    { unit: "days", value: Math.trunc(millis / 86400000) },
    { unit: "hours", value: Math.trunc(millis / 3600000) % 24 },
    { unit: "minutes", value: Math.trunc(millis / 60000) % 60 },
    { unit: "seconds", value: Math.trunc(millis / 1000) % 60 },
    { unit: "milliseconds", value: Math.trunc(millis) % 1000 },
    { unit: "microseconds", value: +millisFraction.slice(0, 3) },
    { unit: "nanoseconds", value: +millisFraction.slice(3, 6) },
  ];
}

/** Options for {@linkcode format}. */
export interface FormatOptions {
  /**
   * The style for formatting the duration.
   *
   * "narrow" for "0d 0h 0m 0s 0ms..."
   * "digital" for "00:00:00:00:000..."
   * "full" for "0 days, 0 hours, 0 minutes,..."
   *
   * @default {"narrow"}
   */
  style?: "narrow" | "digital" | "full";
  /**
   * Whether to ignore zero values.
   * With style="narrow" | "full", all zero values are ignored.
   * With style="digital", only values in the ends are ignored.
   *
   * @default {false}
   */
  ignoreZero?: boolean;
}

/**
 * Format milliseconds to time duration.
 *
 * @example Usage
 * ```ts
 * import { format } from "@std/fmt/duration";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(format(99674, { style: "digital" }), "00:00:01:39:674:000:000");
 *
 * assertEquals(format(99674), "0d 0h 1m 39s 674ms 0µs 0ns");
 *
 * assertEquals(format(99674, { ignoreZero: true }), "1m 39s 674ms");
 *
 * assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minute, 39 seconds, 674 milliseconds");
 * ```
 *
 * @param ms The milliseconds value to format
 * @param options The options for formatting
 * @returns The formatted string
 * @throws {TypeError} If an invalid style option is provided.
 */
export function format(
  ms: number,
  options?: FormatOptions,
): string {
  const {
    style = "narrow",
    ignoreZero = false,
  } = options ?? {};

  const parts = millisecondsToDurationParts(ms);

  switch (style) {
    case "narrow": {
      let arr = parts;
      if (ignoreZero) arr = arr.filter((x) => x.value);
      return arr
        .map((x) => `${x.value}${NARROW_UNIT_NAME_MAP.get(x.unit)}`)
        .join(" ");
    }
    case "full": {
      let arr = parts;
      if (ignoreZero) arr = arr.filter((x) => x.value);
      return arr
        .map((x) => `${x.value} ${getPluralizedKey(x.unit, x.value)}`)
        .join(", ");
    }
    case "digital": {
      const arr = parts.map((x) =>
        ["milliseconds", "microseconds", "nanoseconds"].includes(x.unit)
          ? addZero(x.value, 3)
          : addZero(x.value, 2)
      );
      if (ignoreZero) {
        let cont = true;
        while (cont) {
          if (!Number(arr[arr.length - 1])) arr.pop();
          else cont = false;
        }
      }
      return arr.join(":");
    }
    default: {
      throw new TypeError(`style must be "narrow", "full", or "digital"!`);
    }
  }
}