This is my database example:
[
{
"schedule_time": "2021-05-17 12:39:29",
"slot": "L",
"item_date": "2021-05-18"
},
{
"schedule_time": "2021-05-17 12:47:53",
"slot": "D",
"item_date": "2021-05-18"
},
{
"schedule_time": "2021-05-18 13:55:22",
"slot": "D",
"item_date": "2021-05-19"
},
{
"schedule_time": "2021-05-19 16:09:15",
"slot": "L",
"item_date": "2021-05-20"
},
{
"schedule_time": "2021-05-19 16:11:55",
"slot": "L",
"item_date": "2021-05-20"
},
I want to create a function which will take item_date and it will check the schedule_time is there any same date available or not then it will return schedules something like this 9am to 12am -> 2 Scheduled; 12am to 3pm -> 1 Scheduled; 3pm to 6pm -> 0 Scheduled; 6pm to 9pm -> 2 Scheduled from schedule_time
Also, the problem is the database time format is a 24-hour clock.
For instance, if I click 2021-05-18 then I can see:
9am to 12am -> 2 Scheduled
12am to 3pm -> 1 Scheduled
3pm to 6pm -> 0 Scheduled
6pm to 9pm -> 2 Scheduled
Can anyone give me an idea of how can I make this similar functionality?
CodePudding user response:
To tackle a problem like this it's helpful to think to yourself, "it would be easier if the data looked like X instead." Model out that data. For example, imagine if the data looked like this instead?
const schedulesByDateAndShift = {
"2021-05-17": {
shift1: [
{
"schedule_time": "2021-05-17 12:39:29",
"slot": "L",
"item_date": "2021-05-18"
},
{
"schedule_time": "2021-05-17 12:47:53",
"slot": "D",
"item_date": "2021-05-18"
}
],
shift2: [ /* ... */ ]
},
"2021-05-18": {
/* etc. */
}
};
Then it'd be easy to get what you need, right? Now you just need to figure out how to coerce your current data to this ideal. You can do this by building your data within a loop. It's not clear from your post why the date is different between schedule_time and item_date, but I'll assume for this example that item_date is not relevant and we should use schedule_time only.
const shifts = [
['09:00:00', '12:00:00'],
['12:00:00', '15:00:00'],
['15:00:00', '18:00:00'],
['18:00:00', '21:00:00']
];
const schedulesByDateAndShift = {};
for (const schedule of schedules) {
const [date, time] = schedule.schedule_time.split(' ');
if (!(date in schedulesByDateAndShift)) {
schedulesByDateAndShift[date] = {};
}
const shiftIndex = shifts.findIndex(
([start, end]) => time >= start && time < end
);
if (shiftIndex === -1) {
// TODO: handle case where time doesn't fit within a given shift
continue;
}
const shiftId = `shift${shiftIndex}`;
if (!(shiftId in schedulesByDateAndShift[date])) {
schedulesByDateAndShift[date][shiftId] = [];
}
schedulesByDateAndShift[date][shiftId].push(schedule);
}
