Created
January 2, 2023 14:59
-
-
Save inad9300/31f13f5cfe40400489e8e7b06397bf7f to your computer and use it in GitHub Desktop.
"Humanization" functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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