From d02d71403af609cfc5e4bcf280c145ce10ffad0f Mon Sep 17 00:00:00 2001 From: Griffin Johnston Date: Mon, 23 Dec 2024 23:16:53 -0500 Subject: [PATCH] fix(fmt): add correct pluralization to fmt/duration when using style: full (#6295) --- fmt/duration.ts | 29 ++++++++++++++++++----------- fmt/duration_test.ts | 4 ++-- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/fmt/duration.ts b/fmt/duration.ts index d116340aed06..3cf878a4ca30 100644 --- a/fmt/duration.ts +++ b/fmt/duration.ts @@ -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 */ @@ -34,15 +34,20 @@ interface DurationObject { } const keyList: Record = { - 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 @@ -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 @@ -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": { diff --git a/fmt/duration_test.ts b/fmt/duration_test.ts index 27d0edaff142..988c9c8ea2fe 100644 --- a/fmt/duration_test.ts +++ b/fmt/duration_test.ts @@ -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", ); }, }); @@ -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", ); }, });