Home > database >  How can I check for overlapping dates in Typescript (without multiple iterations if possible)?
How can I check for overlapping dates in Typescript (without multiple iterations if possible)?

Time:10-26

I have a function which declares and populates an array of dates:

 let dateArray: { startDate: Date, endDate: Date }[] = [];
 let dateVal = {startDate: new Date('2022-09-05'), endDate: new Date('2022-09-23')};
 dateArray.push(dateVal);
 dateVal = {startDate: new Date('2022-10-01'), endDate: new Date('2022-10-31')};
 dateArray.push(dateVal);

I need to check that none of the dates overlap; in the example above there is no overlap because the first date range ends on 23 September, whereas the second starts on 1 October. However, if I add a new value:

 dateVal = {startDate: new Date('2022-10-21'), endDate: new Date('2022-11-14')};
 dateArray.push(dateVal)

then there is an overlap because it starts on 21 October which is before the end of the second value (31 October). Can anyone think of a good way to determine if there are any overlaps in the values in dateArray? The maximum feasible number of array elements is probably 10-20. I can see a brute force approach but an elegant solution would be good! Thank you.

CodePudding user response:

A clean but not fastest way:

const sortedArray = dateArray.sort((left,right)=>left.startDate.valueOf() 
- right.startDate.valueOf() 
const isOverlaped = ()=>{
  for(let index =1;index< sortedArray.length;index  ){
    if(sortedArray[index-1].endDate.valueOf() - sortedArray[index].startDate.valueOf() >= 0){
      return true
    }
  }
  return false
}

Try to use reduce to make it more "elegant".

const sortedArray = dateArray.sort((left,right)=>left.startDate.valueOf() 
- right.startDate.valueOf()
let isOverlaped = false; 
sortedArray.reduce((left,right)=>{
  if(left.endDate.valueOf() - right.startDate.valueOf() >= 0 ){
    isOverlaped = true
  }
  return right
}) 
// you can use isOverlaped

  • Related