Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions fmt/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
*
* assertEquals(format(99674, { ignoreZero: true }), "1m 39s 674ms");
*
* assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minutes, 39 seconds, 674 milliseconds");
* assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minute, 39 seconds, 674 milliseconds");
* ```
* @module
*/
Expand All @@ -34,15 +34,20 @@ interface DurationObject {
}

const keyList: Record<keyof DurationObject, string> = {
d: "days",
h: "hours",
m: "minutes",
s: "seconds",
ms: "milliseconds",
us: "microseconds",
ns: "nanoseconds",
d: "day",
h: "hour",
m: "minute",
s: "second",
ms: "millisecond",
us: "microsecond",
ns: "nanosecond",
};

/** Get key with pluralization */
function getPluralizedKey(type: keyof DurationObject, value: number) {
return value === 1 ? keyList[type] : `${keyList[type]}s`;
}

/** Parse milliseconds into a duration. */
function millisecondsToDurationObject(ms: number): DurationObject {
// Duration cannot be negative
Expand Down Expand Up @@ -109,7 +114,7 @@ export interface FormatOptions {
*
* assertEquals(format(99674, { ignoreZero: true }), "1m 39s 674ms");
*
* assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minutes, 39 seconds, 674 milliseconds");
* assertEquals(format(99674, { style: "full", ignoreZero: true }), "1 minute, 39 seconds, 674 milliseconds");
* ```
*
* @param ms The milliseconds value to format
Expand Down Expand Up @@ -146,12 +151,14 @@ export function format(
if (ignoreZero) {
return `${
durationArr.filter((x) => x.value).map((x) =>
`${x.value} ${keyList[x.type]}`
`${x.value} ${getPluralizedKey(x.type, x.value)}`
).join(", ")
}`;
}
return `${
durationArr.map((x) => `${x.value} ${keyList[x.type]}`).join(", ")
durationArr.map((x) =>
`${x.value} ${getPluralizedKey(x.type, x.value)}`
).join(", ")
}`;
}
case "digital": {
Expand Down
4 changes: 2 additions & 2 deletions fmt/duration_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Deno.test({
fn() {
assertEquals(
format(99674, { style: "full" }),
"0 days, 0 hours, 1 minutes, 39 seconds, 674 milliseconds, 0 microseconds, 0 nanoseconds",
"0 days, 0 hours, 1 minute, 39 seconds, 674 milliseconds, 0 microseconds, 0 nanoseconds",
);
},
});
Expand Down Expand Up @@ -62,7 +62,7 @@ Deno.test({
fn() {
assertEquals(
format(99674, { style: "full", ignoreZero: true }),
"1 minutes, 39 seconds, 674 milliseconds",
"1 minute, 39 seconds, 674 milliseconds",
);
},
});
Expand Down
Loading