R
E
A
C
T
O
xamplesÂ
epeat
ode
pproach
ptimize
est
{Clock Minute Adder}
The Question
Given a current time in the string format "HH:MM" and a number of minutes, return the clock time given those minutes added to the base time. Assume you're working with a standard 12-hour clock and the output should match the input format "HH:MM".
Examples
addMinutes('1:30', 30); // 2:00
addMinutes('12:30', 40); // 1:10
addMinutes('11:59', 1); // 12:00
addMinutes('1:59', 240); // 5:59
addMinutes('1:23', 456789); // 6:32
Approach
1. Convert the inputed time into hours and minutes
2. Add together the inputed time to be total minutes
3. Add the inputed total minutes to the added minutes
4. Convert the new total time into hours and minutes
5. Return the new time in the correct format
The Solution
function addMinutes (oldTime, minLater) {
const [oldHrs, oldMins] = oldTime.split(':')
.map(str => Number(str))
const oldTotalMins = (oldHrs * 60) + oldMins
const newTotalMins = oldTotalMins + minLater
const totalHrs = Math.floor(newTotalMins / 60)
const newHrs = ((totalHrs - 1) % 12) + 1
const newMins = newTotalMins % 60
return `${newHrs}:${newMins > 9 ? newMins : `0${newMins}`}`
}
There's one edge case to consider. The hours are "one-indexed" not "zero-indexed", ie. there's no such time as 0:40, instead it's 12:40. To solve this, we can subtract 1 then mod by 12 then add 1.
Try it out @ https://repl.it/Ig38/1
Reacto: Clock Minute Adder
By sarahdherr
Reacto: Clock Minute Adder
- 704