Last active
May 14, 2020 10:08
-
-
Save barnslig/be6185fcd47f6f7c0897647a1becf887 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
| /** | |
| * Parse a duration string | |
| * | |
| * A duration string is a sequence of decimal numbers, each with optional | |
| * fraction and a unit suffix such as "300ms", "1.5h", "2h45m12s" etc. | |
| * | |
| * Valid units are: "h", "m", "s", "ms" | |
| * | |
| * A decimal without unit is considered to be a second, e.g. "1m13" === "1m13s". | |
| * | |
| * @param {String} duration - Duration string formatted as specified above | |
| * @returns {Number} The parsed duration in seconds | |
| */ | |
| const parseDuration = (duration) => | |
| duration | |
| .match(/(\d+(\.\d+)?(ms|s|m|h)?)/g) | |
| .map((t) => { | |
| if (t.slice(-1) === "h") { | |
| return parseFloat(t.slice(0, -1)) * 3600; | |
| } | |
| if (t.slice(-1) === "m") { | |
| return parseFloat(t.slice(0, -1)) * 60; | |
| } | |
| if (t.slice(-2) === "ms") { | |
| return parseFloat(t.slice(0, -2)) / 1000; | |
| } | |
| return parseFloat(t); | |
| }) | |
| .reduce((acc, cur) => acc + cur); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment