formatDuration
EditFormats milliseconds as a compact multi-unit duration.
type DurationUnit = { label: string; milliseconds: number };const units: DurationUnit[] = [ { label: "d", milliseconds: 86_400_000 }, { label: "h", milliseconds: 3_600_000 }, { label: "m", milliseconds: 60_000 }, { label: "s", milliseconds: 1_000 }, { label: "ms", milliseconds: 1 },];
export type FormatDurationOptions = { maxUnits?: number;};
/** Formats milliseconds as a compact duration with a limited number of units. */export const formatDuration = ( milliseconds: number, { maxUnits = 2 }: FormatDurationOptions = {}): string => { if (!Number.isFinite(milliseconds)) throw new RangeError("milliseconds must be finite"); if (!Number.isSafeInteger(maxUnits) || maxUnits < 1 || maxUnits > units.length) { throw new RangeError(`maxUnits must be an integer from 1 to ${units.length}`); } const sign = milliseconds < 0 ? "-" : ""; let remaining = Math.round(Math.abs(milliseconds)); if (remaining === 0) return "0 ms"; const parts: string[] = []; for (const unit of units) { const amount = Math.floor(remaining / unit.milliseconds); if (amount === 0 && parts.length === 0) continue; if (amount > 0) { parts.push(`${amount} ${unit.label}`); remaining -= amount * unit.milliseconds; } if (parts.length === maxUnits) break; } return sign + parts.join(" ");};Download
Section titled “Download”wget -O src/lib/formatDuration.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/formatDuration.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/formatDuration.ts" src/lib/formatDuration.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { formatDuration } from "./formatDuration";
formatDuration(90_500);// "1 m 30 s"
formatDuration(90_500, { maxUnits: 3 });// "1 m 30 s 500 ms"milliseconds(number) — Finite duration, rounded to whole milliseconds.maxUnits(number) — Number of displayed non-zero units from1to5.- Supports days through milliseconds and negative durations.