Skip to content

Instantly share code, notes, and snippets.

@inad9300
Created January 2, 2023 14:59
Show Gist options
  • Save inad9300/31f13f5cfe40400489e8e7b06397bf7f to your computer and use it in GitHub Desktop.
Save inad9300/31f13f5cfe40400489e8e7b06397bf7f to your computer and use it in GitHub Desktop.
"Humanization" functions.
export function humanizeBytes(bytes: number): string {
if (bytes < 1000) return bytes + ' B';
const kb = bytes / 1000;
if (kb < 1000) return kb.toFixed(2) + ' KB';
const mb = kb / 1000;
if (mb < 1000) return mb.toFixed(2) + ' MB';
const gb = mb / 1000;
return gb.toFixed(2) + ' GB';
}
const durationUnits = {
d: 24 * 60 * 60_000,
h: 60 * 60_000,
min: 60_000,
s: 1_000,
ms: 1
};
export function humanizeDuration(totalMs: number): string {
let result = '';
for (const unitName of keys(durationUnits)) {
const unitMs = durationUnits[unitName];
const wholeUnits = Math.floor(totalMs / unitMs);
if (wholeUnits !== 0) {
result += wholeUnits + unitName + ' ';
totalMs -= wholeUnits * unitMs;
}
}
return result ? result.trim() : '0ms';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment