Created
June 25, 2021 10:14
-
-
Save t1mofe1/a86493ef652ca1e833a0d85f06587335 to your computer and use it in GitHub Desktop.
Time string formatter
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
/** | |
* @function formatTime | |
* @param {string} str - string with all times joined with space. Ex: "10s 4m" | |
* @returns {string} total time in milliseconds | |
*/ | |
module.exports = function formatTime(str) { | |
let totalTime = 0; | |
str.split(' ').forEach((field) => { | |
field = field.trim(); | |
const regex = /(?<time>[0-9]{1,})(?<type>ms|s|m|h|d|w)/gi; | |
if (!regex.test(field)) return; | |
regex.lastIndex = 0; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex | |
let { time, type } = regex.exec(field).groups; | |
time = Number(time); // convert "time" to number because of JS.. 0 + "123" = "0123" | |
switch (type) { | |
case 'ms': | |
totalTime += time; | |
break; | |
case 's': | |
totalTime += time * 1000; | |
break; | |
case 'm': | |
totalTime += time * 1000 * 60; | |
break; | |
case 'h': | |
totalTime += time * 1000 * 60 * 60; | |
break; | |
case 'd': | |
totalTime += time * 1000 * 60 * 60 * 24; | |
break; | |
case 'w': | |
totalTime += time * 1000 * 60 * 60 * 24 * 7; | |
break; | |
} | |
}); | |
return totalTime; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment