Home > OS >  how to find conflicts in time slot without moment
how to find conflicts in time slot without moment

Time:10-11

I have the below list if the selected timeslot is conflicted then return true else false.

I tried doing this but it is not working

return list.some(item => {
            if (new Date(item.startDate).getTime() <= new Date(selectedStartDate).getTime() && new Date(item.endDate).getTime() > new Date(selectedStartDate).getTime()) {
                return true;
            }
            if (new Date(item.startDate).getTime() < new Date(selectedEndDate).getTime() && new Date(item.endDate).getTime() > new Date(selectedEndDate).getTime()) {
                return true;
            }
            return false
        })
const list = [
 { 
 startDate: new Date('2022-10-10T11:00:00')
 endDate: new Date('2022-10-10T11:30:00') 
} ,
 { 
 startDate: new Date('2022-10-10T12:00:00')
 endDate: new Date('2022-10-10T13:00:00') 
}
]

test 1:

const selectedSlot = {
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T12:30:00')
}

test 2:

const selectedSlot = {
startDate: new Date('2022-10-10T10:30:00'),
endDate: new Date('2022-10-10T11:30:00')
}

test 3:

const selectedSlot = {
startDate: new Date('2022-10-11T10:30:00'),
endDate: new Date('2022-10-11T11:30:00')
}

CodePudding user response:

You can compare ISO 8601 date strings resp. JavaScript date objects. You have a conflict if startDate1 < endDate2 && startDate2 < endDate1. Compare the selected slot with each element in the list.

function isConflict(list, {startDate: startDate2, endDate: endDate2}) {
  return list.some(({startDate: startDate1, endDate: endDate1}) => startDate1 < endDate2 && startDate2 < endDate1);
}

const list = [{ 
  startDate: new Date('2022-10-10T11:00:00'),
  endDate: new Date('2022-10-10T11:30:00') 
}, { 
  startDate: new Date('2022-10-10T12:00:00'),
  endDate: new Date('2022-10-10T13:00:00') 
}];

const tests = [{
  startDate: new Date('2022-10-10T10:30:00'),
  endDate: new Date('2022-10-10T12:30:00')
}, {
  startDate: new Date('2022-10-10T10:30:00'),
  endDate: new Date('2022-10-10T11:30:00')
}, {
  startDate: new Date('2022-10-11T10:30:00'),
  endDate: new Date('2022-10-11T11:30:00')
}];

for (const test of tests) {
  console.log(isConflict(list, test));
}

  • Related