Skip to content

Commit

Permalink
fix: include undefined values if formatting with zero option set to true
Browse files Browse the repository at this point in the history
  • Loading branch information
tommaso-sebastianelli committed Feb 7, 2024
1 parent 6f44a16 commit f2b2950
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
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",
);
});
});

0 comments on commit f2b2950

Please sign in to comment.