Created
August 30, 2023 22:50
-
-
Save dmgolembiowski/520d223a237e61eb0abf2c1dabfa2dc3 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
function crunchtime(input) { | |
// time should be a delta from some time Xa-Ya, | |
// Xa-Y, Xp-Yp | |
// This function parses the first non-numeric character | |
// as an indication of whether it's receiving AM or PM, | |
// followed by a `-` to delimit between the starting time | |
// and ending time. Our expected inputs, less formally, resemble | |
// 4:45a-11a, 5p-12:30p, 6:45a-2p | |
input = input.trim(); | |
if (input.toLowerCase() == "off") { | |
return 0; | |
} | |
let [start, end] = input.split('-'); | |
let hours = 0; | |
let minutes = 0; | |
let startMin = timeToMin(start); | |
let endMin = timeToMin(end); | |
let delta = endMin - startMin; | |
hours += Math.floor(delta / 60.0); | |
minutes += delta - (hours * 60.0); | |
hours += (minutes / 60.0); | |
return hours; | |
} | |
function timeToMin(timestr) { | |
const minPerHour = 60; | |
const minPerTwelveHours = minPerHour * 12; | |
let minutes = 0; | |
if (!(timestr.includes(':'))) { | |
let m = [...timestr].reverse().join("")[0].toLowerCase(); | |
switch (m) { | |
case 'a': { | |
let accum = timestr.replace('/a$/', ''); | |
accum = parseInt(accum, radix=10); | |
if (accum == 12) { | |
minutes += 2 * minPerTwelveHours; | |
} | |
else { | |
minutes += accum * minPerHour; | |
} | |
}; | |
break; | |
case 'p': { | |
let accum = timestr.replace('/p$/', ''); | |
accum = parseInt(accum, radix=10); | |
minutes += minPerTwelveHours; | |
if (accum < 12) { | |
minutes += accum * minPerHour; | |
} | |
}; | |
break; | |
default: { | |
return -1; | |
}; | |
break; | |
} | |
} | |
else | |
{ | |
let m = [...timestr].reverse().join("")[0].toLowerCase(); | |
switch (m) { | |
case 'a': { | |
let combined = timestr.replace('/a$/', ''); | |
let [h, s] = combined.split(':'); | |
let am_hours = parseInt(h, radix=10); | |
let am_mins = parseInt(s, radix=10); | |
if (am_hours == 12) { | |
minutes += 2 * minPerTwelveHours; | |
minutes += am_mins; | |
} | |
else { | |
minutes += am_hours * minPerHour; | |
minutes += am_mins; | |
} | |
}; | |
break; | |
case 'p': { | |
let combined = timestr.replace('/p$/', ''); | |
let [h, s] = combined.split(':'); | |
let pm_hours = parseInt(h, radix=10); | |
let pm_mins = parseInt(s, radix=10); | |
minutes += minPerTwelveHours; | |
if (pm_hours < 12) { | |
minutes += pm_mins * minPerHour; | |
} | |
}; | |
break; | |
default: { return -2; }; | |
break; | |
} | |
} | |
return minutes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment