There is a question that is tricky. Make a function that takes a string argument like 2:00 p.m. or 5:50 a.m.
You must not use momentjs or any other third-party library.
We have three static hours to determine the difference between them and this argument.
7:00 a.m. for breakfast.
12:00 p.m. for lunch.
7:00 p.m. for dinner.
The function should return an array with the first and second elements representing hours and minutes, like below:
timeToEat("2:00 a.m.") // [5, 0];
timeToEat("5:50 p.m.") // [1, 10];
CodePudding user response:
You can start by creating a minutesSinceMidnight() function to get the time since midnight in minutes for a given input string.
We'll then create the timeToEat() function, which will start by finding the next meal time.
Once this is found, we'll get the time to the next meal in minutes, and convert to hours and minutes using
a minutesToHoursAndMinutes() function.
function minutesSinceMidnight(timeStr) {
let rg = /(\d{1,2})\:(\d{1,2})\s ([ap])\.?m/
let [,hour, minute, am] = rg.exec(timeStr);
hour = Number(hour);
if (am === 'a' && hour === 12) hour -= 12;
if (am === 'p' && hour < 12) hour = 12;
return hour * 60 Number(minute);
}
function minutesToHoursAndMinutes(totalMinutes) {
let hours = Math.floor(totalMinutes / 60);
let minutes = totalMinutes % 60;
return [ hours, minutes]
}
function timeToEat(timeStr) {
let currentTime = minutesSinceMidnight(timeStr);
let mealTimes = ['7:00 a.m', '12:00 p.m.', '7:00 p.m.'].map(minutesSinceMidnight);
let nextMealTime = mealTimes.find(mealTime => mealTime >= currentTime);
// No meal found...
if (nextMealTime === undefined) {
return nextMealTime;
}
let timeToNextMealMinutes = nextMealTime - currentTime;
return minutesToHoursAndMinutes(timeToNextMealMinutes);
}
console.log(timeToEat("2:00 a.m."));
console.log(timeToEat("5:50 p.m."));
console.log(timeToEat("6:30 p.m."));
.as-console-wrapper { max-height: 100% !important; top: 0; }
