Created
March 27, 2021 18:07
-
-
Save colbyfayock/e25b5b9cf0e187ff1092e38ad3ee3750 to your computer and use it in GitHub Desktop.
Parse human readable time in minutes and seconds
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 parseHumanTime(string) { | |
const units = { | |
'm': 'minutes', | |
'min': 'minutes', | |
'mins': 'minutes', | |
'minutes': 'minutes', | |
's': 'seconds', | |
'sec': 'seconds', | |
'secs': 'seconds', | |
'seconds': 'seconds' | |
}; | |
const numbers = []; | |
const letters = []; | |
string.split('').forEach(char => { | |
if ( char === ' ' ) return; | |
if ( isNaN(parseInt(char)) ) { | |
letters.push(char); | |
return; | |
} | |
if ( letters.length === 0 ) { | |
numbers.push(char); | |
return; | |
} | |
const error = new Error('Invalid time. Format is not recognizable.'); | |
error.name = 'INVALID_TIME_FORMAT'; | |
throw error; | |
}); | |
const number = parseInt(numbers.join('')); | |
const letter = letters.join(''); | |
const unit = units[letter]; | |
if ( !unit ) { | |
const error = new Error('Invalid time. Can not recognize unit.'); | |
error.name = 'INVALID_TIME_UNIT'; | |
throw error; | |
} | |
return { | |
number, | |
unit | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment