Last active
October 14, 2020 20:05
-
-
Save Legend-of-iPhoenix/c022975710503144c6d02e9f5c82d592 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// formats a duration as a human readable string, ex. "5 days, 4 minutes, and 1 second ago". | |
function formatDuration(ms) { | |
let parts = []; | |
const addPart = (value, maxValue, label) => { | |
value = Math.floor(value) % maxValue; | |
if (value > 0) { | |
parts.unshift(value + " " + label + (value === 1 ? "" : "s")); | |
} | |
} | |
const seconds = ms / 1000; | |
addPart(seconds, 60, "second"); | |
const minutes = seconds / 60; | |
addPart(minutes, 60, "minute"); | |
const hours = minutes / 60; | |
addPart(hours, 24, "hour"); | |
const days = hours / 24; | |
addPart(days, Infinity, "day"); | |
let result = ""; | |
switch (parts.length) { | |
case 0: { | |
return "now"; | |
}; | |
case 1: | |
case 2: { | |
return parts.join(" and ") + " ago"; | |
}; | |
default: { | |
parts.push("and " + parts.pop()); | |
return parts.join(", ") + " ago"; | |
} | |
} | |
} | |
// reuse allowed with attribution |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment