Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created June 12, 2020 12:15
Show Gist options
  • Save cristobal/740e0f259d14343322da0eeb12dae7df to your computer and use it in GitHub Desktop.
Save cristobal/740e0f259d14343322da0eeb12dae7df to your computer and use it in GitHub Desktop.
function parseDesignators (duration) {
return [
{
name: 'hours',
designator: 'H'
},
{
name: 'minutes',
designator: 'M'
},
{
name: 'seconds',
designator: 'S'
}
].reduce(
(acc, item) => {
const index = duration.indexOf(item.designator)
if (index !== -1) {
acc[item.name] = index
}
return acc
},
{}
)
}
function parseHours (duration, designators) {
if (!designators.hours) {
return '0'
}
// always start after the PT
return duration.substring(2, designators.hours)
}
function parseMinutes(duration, designators) {
if (!designators.minutes) {
return '0'
}
// start after the hours designator if present
if (designators.hours) {
return duration.substring(designators.hours + 1, designators.minutes)
}
// always start after the PT if hours is not present
return duration.substring(2, designators.minutes)
}
function parseSeconds(duration, designators) {
if (!designators.seconds) {
return '0'
}
// start after the minutes designator if present
if (designators.minutes) {
return duration.substring(designators.minutes + 1, designators.seconds)
}
// start after the hours designator if present and hours is not present
if (designators.hours) {
return duration.substring(designators.hours + 1, designators.seconds)
}
// always start after the PT if neither hours or minutes is present
return duration.substring(2, designators.seconds)
}
function parseDuration (duration) {
const designators = parseDesignators(duration)
return {
hours: Number(parseHours(duration, designators)),
minutes: Number(parseMinutes(duration, designators)),
seconds: Number(parseSeconds(duration, designators))
}
}
function parseDurationToSeconds(duration) {
const values = parseDuration(duration)
return (values.hours * 3600) + (values.minutes * 60) + values.seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment