I have an array of times (these are not constant) [1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00]
. The goal is to calculate times that can be bookable. If there is an existing booking from 4:00 - 5:00
then 3:00
should be unavailable as it would overlap the existing booking. To calculate this, I have a function that tells us the start and end indexes of the booking, I need to find a way to remove x times from behind the start index.
To make it more clear, I drew a diagram.
Doing this calculation will allow to calculate available times no matter how long the existing booking is. I'm trying to figure out how to create a function that does what I described. Below is the code I have to return the available times based on the start/end index provided however I'm stuck on how to approach the calculation I described above.
// This filters times that are less than the start index
const filteredTimes1 = availableHours.filter((item, index) => index < (
(startTimeIndex || availableHours.length - 0)
))
// This filters times that greater than the end index
const filteredTimes2 = availableHours.filter((item, index) =>
index > (endTimeIndex || availableHours.length)
)
// Then combine the results into an array
const validAvailableHours = [...filteredTimes1 , ...filteredTimes2]
Any help would be appreciated, thanks.
CodePudding user response:
You're way overcomplicating this.
Just keep a map of the times already booked, in this case 4pm. Later add 3pm since you're adding that too.
Or if you want it simpler just use a Set.
const bookedHours = new Set()
// too add booked times
bookedHours.add(4)
// to get an array with available times
const available = [1,2,3,4,5,23,24]
const availableUpdate = available.filter(n => !bookedHours.has(n))
CodePudding user response:
I mean you could simply use array.slice() to do the trick.
let allHours = [1, 2, 3, 4, 5, 6, 7]
let [startHours, endHours] = [4, 5];
let duration = 1;
let availableHours = [
...allHours.slice(
0,
allHours.indexOf(startHours - duration)
),
...allHours.slice(
allHours.indexOf(endHours 1)
)]
console.log(availableHours)