Last active
October 20, 2021 01:04
-
-
Save mgtitimoli/f2771d0eb2f44ac2099d1b4aca175bb3 to your computer and use it in GitHub Desktop.
Time difference
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
const time24TupleToMinutes = ([hours, minutes]) => hours * 60 + minutes; | |
const timeStrToTuple = timeStr => timeStr.split(":").map(Number); | |
const time12ToTime24Tuple = time12 => { | |
const [hours, minutes] = timeStrToTuple(time12.slice(0, -2)); | |
const amPm = time12.slice(-2); | |
return [ | |
amPm === "am" | |
? hours === 12 ? hours - 12 : hours | |
: hours < 12 ? hours + 12 : hours, | |
minutes | |
]; | |
}; | |
const dayMinutes = 24 * 60; | |
const getRelativeMinutesDiff = (minutes0, minutes1) => | |
minutes0 > minutes1 | |
? dayMinutes - minutes0 + minutes1 | |
: minutes1 - minutes0; | |
const getAbsoluteMinutesDiff = (minutes0, minutes1) => Math.abs(firstTimeMinutes - secondTimeMinutes); | |
function StringChallenge(str) { | |
const time12s = str.split("-"); | |
const time24Tuples = time12s.map(time12ToTime24Tuple); | |
const [firstTimeMinutes, secondTimeMinutes] = time24Tuples.map(time24TupleToMinutes); | |
return getAbsoluteMinutesDiff(firstTimeMinutes, secondTimeMinutes); | |
} | |
console.log(StringChallenge("12:30pm-12:00am")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment