javascriptarraysappointmenttimeslots

Javascript - Timeslots handling by removing service duration


I am new to this forum, and I came here because my brains are exploding but I really would like to achieve building an booking system application. The Following is my story:

I am working with the following data:

  • An Array with timeslots which have 5 minutes in between them, so that the user can select a timeslot to book his appointment. It looks like below:

var timeslotArray = ["09:00", "09:05", "09:10", "09:15", "09:20", "09:25" ... ,"18:00"]

NOTE: I removed from the "timeslotArray" already some times, for example like a break from "12:00" till "13:00". Or if there are other appointments, then I managed to remove those times. So I end up with a "timeslotArray" which looks like:

var timeslotArray = ["09:00", "09:05", "09:25" ... ,"18:00"]

Next there are services which can be booked, and these services have durations. Let's say the user selected a service with a duration of 10 minutes. Now my big question is how can I remove the duration of the service from the "timeslotArray" so that the user only can select the available timeslots. Because now there is a break from 09:10 till 09:25. This means that 09:05 should not be visible in the "timeslotArray" because the service duration is 10 minutes.(begin break is 09:10, minus 10 minutes is 09:00). Also keep in mind that there are next to the breaks also other appointments which I need to remove 10 min from the starting time.

I am working fully in Javascript and have tried a lot, but there was always at least one scenario which I had not covered during the coding.

I hope there is someone who can help me even if it is a small step. Thanks anyway!

Kind regards,

Hanake


Solution

  • how you doing?

    Check this code:

    var timeslotArray = ["09:00", "09:05", "09:10", "09:15", "09:20", "09:25","18:00"]
    
    function updateArray(timeChosen,duration){
    var startTime = new Date(Date.parse('01/01/2011 '+timeChosen));
    var endTime =  new Date(startTime.getTime() + duration * 60000);
    
    timeslotArray.forEach((hour, index)=>{
    var hourAsDate = new Date(Date.parse('01/01/2011 '+ hour));
    if (hourAsDate < endTime && hourAsDate >= startTime){
    timeslotArray[index] = null; 
    }
    });
    timeslotArray = timeslotArray.filter((hour) => {return hour != null;});
    }
    
    updateArray("09:00",20);
    console.log(timeslotArray);

    the function updateArray should get a string of an hour (eg. "05:00" or "09:00") and a number for duration (which indicate minutes).

    The array are going through a forEach command that makes all the hours between the start time and the end time null, and afterwards filter all the nulls out (I did that so because removing parts of an array inside a loop causes indexing troubles)

    Have fun hacking!