Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

formatDuration: Include undefined values if formatting with zero option set to true #3703

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/formatDuration/index.ts
Expand Up @@ -105,7 +105,7 @@ export function formatDuration(
const token = `x${unit.replace(/(^.)/, (m) =>
m.toUpperCase(),
)}` as FormatDistanceToken;
const value = duration[unit];
const value = duration[unit] ?? (zero ? 0 : undefined);
if (value !== undefined && (zero || duration[unit])) {
return acc.concat(locale.formatDistance(token, value));
}
Expand Down
34 changes: 34 additions & 0 deletions src/formatDuration/test.ts
Expand Up @@ -77,4 +77,38 @@ describe("formatDuration", () => {
"9 months, 2 days",
);
});

it("allows to provide a custom locale formatter", () => {
assert(
formatDuration(
{
hours: 1,
minutes: 10,
seconds: 30,
},
{
delimiter: ":",
format: ["hours", "minutes", "seconds"],
locale: {
formatDistance: (_, count) => String(count).padStart(2, "0"),
},
zero: true,
},
) === "01:10:30",
);
});

it("includes undefined duration values when formatting if zero is true", () => {
assert(
formatDuration(
{
seconds: 10,
},
{
format: ["hours", "minutes", "seconds"],
zero: true,
},
) === "0 hours 0 minutes 10 seconds",
);
});
});