Created
July 9, 2020 02:42
-
-
Save MRuy/0363e932001cd2905f5dc62f9e3348b1 to your computer and use it in GitHub Desktop.
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
/** | |
* Returns the time string as Number in seconds. | |
* @param {string} str - String with human readable time for example "15m 45s" | |
* @returns {number} Seconds as Number | |
*/ | |
function humanReadableTimeStringToSeconds(str) { | |
const units = ['d', 'h', 'm', 's']; | |
const regex = RegExp('^(\\d+)(['+units.join('')+'])$', 'i'); | |
const unitConversions = [86400, 3600, 60, 1]; | |
const parts = str.split(/\s+/) || [str]; | |
return parts.reduce((a, c) => { | |
const m = c.match(regex); | |
if (m === null) { | |
return a; | |
} | |
const val = Number(m[1]); | |
const unit = m[2]; | |
return a + (val * unitConversions[units.indexOf(unit)]); | |
}, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment