Skip to content

Instantly share code, notes, and snippets.

@MRuy
Created July 9, 2020 02:42
Show Gist options
  • Save MRuy/0363e932001cd2905f5dc62f9e3348b1 to your computer and use it in GitHub Desktop.
Save MRuy/0363e932001cd2905f5dc62f9e3348b1 to your computer and use it in GitHub Desktop.
/**
* 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