Skip to content

Instantly share code, notes, and snippets.

@colbyfayock
Created March 27, 2021 18:07
Show Gist options
  • Save colbyfayock/e25b5b9cf0e187ff1092e38ad3ee3750 to your computer and use it in GitHub Desktop.
Save colbyfayock/e25b5b9cf0e187ff1092e38ad3ee3750 to your computer and use it in GitHub Desktop.
Parse human readable time in minutes and seconds
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