This commit is contained in:
thororen 2024-04-17 14:29:47 -04:00
parent 538b87062a
commit ea7451bcdc
326 changed files with 24876 additions and 2280 deletions

View file

@ -93,6 +93,39 @@ export function formatDuration(time: number, unit: Units, short: boolean = false
return res.length ? res : `0 ${getUnitStr(unit, false, short)}`;
}
/**
* The `formatDurationMs` function formats a duration in milliseconds into a human-readable string,
* with the option to include units such as days, hours, minutes, and seconds.
* @param {number} ms - The `ms` parameter represents the duration in milliseconds that you want to
* format.
* @param {boolean} [human=false] - The `human` parameter is a boolean flag that determines whether the
* duration should be formatted in a human-readable format or not. If `human` is set to `true`, the
* duration will be formatted as "Xd Xh Xm Xs". If `human` is set to `false` (the default), the
* duration will be formatted as "XX:XX:XX:XX".
* @returns The function `formatDurationMs` returns a formatted string representing the duration in
* milliseconds.
*/
export function formatDurationMs(ms: number, human: boolean = false, seconds: boolean = true) {
const format = (n: number) => human ? n : n.toString().padStart(2, "0");
const unit = (s: string) => human ? s : "";
const delim = human ? " " : ":";
// thx copilot
const d = Math.floor(ms / 86400000);
const h = Math.floor((ms % 86400000) / 3600000);
const m = Math.floor(((ms % 86400000) % 3600000) / 60000);
const s = Math.floor((((ms % 86400000) % 3600000) % 60000) / 1000);
let res = "";
if (d) res += `${d}${unit("d")}${delim}`;
if (h || res || !seconds) res += `${format(h)}${unit("h")}${delim}`;
if (m || res || !human || !seconds) res += `${format(m)}${unit("m")}`;
if (seconds && (m || res || !human)) res += `${delim}`;
if (seconds) res += `${format(s)}${unit("s")}`;
return res;
}
/**
* Join an array of strings in a human readable way (1, 2 and 3)
* @param elements Elements