25 lines
830 B
JavaScript
25 lines
830 B
JavaScript
(function exposeDurationFormatter(root, factory) {
|
|
const formatter = factory();
|
|
if (typeof module === "object" && module.exports) {
|
|
module.exports = formatter;
|
|
} else {
|
|
root.NCCFormatDuration = formatter;
|
|
}
|
|
}(globalThis, () => function formatDuration(value) {
|
|
if (typeof value !== "string") return value;
|
|
const match = value.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
|
|
if (!match || !match.slice(1).some((part) => part !== undefined)) return value;
|
|
|
|
const units = [
|
|
[match[1], "day"],
|
|
[match[2], "hr"],
|
|
[match[3], "min"],
|
|
[match[4], "sec"]
|
|
].filter(([amount]) => Number(amount) > 0);
|
|
|
|
if (!units.length) return "0 min";
|
|
return units.map(([amount, unit]) => (
|
|
`${Number(amount)} ${unit}${unit === "day" && Number(amount) !== 1 ? "s" : ""}`
|
|
)).join(" ");
|
|
}));
|