i should generate an array of strings that maps time pairs to me every half hour, starting from a departure time like 1pm and an end time like 11pm, that i can dynamically create an array of this type:
return ['13: 00-13: 30 ',' 13: 30-14: 00 ',' 14: 00-14: 30 ',' 14: 30-15: 00 ',' 15: 00-15: 30 ', '20: 00-20: 30', '20: 30-21: 00', '21: 00-21: 30', '21: 30-22: 00', '22: 00-22: 30 ']
I had found an approach but was unable to adapt it to my needs:
function getTimes(start, end) {
start = parseInt(start) * 2 + (+start.slice(-2) > 0);
end = parseInt(end) * 2 + (+end.slice(-2) > 0) + 1;
return Array.from({length: end - start}, (_, i) =>
(((i + start) >> 1) + ":" + ((i + start)%2*3) + "0").replace(/^\d:/, "0$&"));
};
console.log(getTimes("13:00", "24:00"));
I get an output like this, which is not good:
[ '13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00',
'18:30',
'19:00',
'19:30',
'20:00',
'20:30',
'21:00',
'21:30',
'22:00',
'22:30',
'23:00',
'23:30',
'24:00' ]
I'd just track everything in minutes, with two helpers for conversion between strings and minutes:
function parseTime(timeString) {
let time = timeString.split(":");
return time[0] * 60 + time[1] * 1;
}
function timeString(time) {
let h = Math.floor(time / 60);
if (h > 23) h -= 24;
let m = time % 60;
return h.toString().padStart(2, "0") + ":" + m.toString().padStart(2, "0");
}
function getTimes(start, end) {
start = parseTime(start);
end = parseTime(end);
if (end < start) end += 24 * 60;
let result = [];
while (start < end) {
result.push(timeString(start) + "-" + timeString(start + 30));
start += 30;
}
return result;
}
console.log(getTimes("13:00", "24:00"));