Home > other >  How to calculate time overlapping in Javascript
How to calculate time overlapping in Javascript

Time:03-29

I want o find overlapped time slot with small code. Lets there are time slots:

const slots = [
    {
    start_time: '10:30',
    end_time: '11:00'
  },
  {
    start_time: '11:30',
    end_time: '12:00'
  }
]

And I got the value from user as:

const inputStartTime = '10:50';
const inputEndTime = '11:20';

I think, there will be no overlapping if inputStartTime > slots.end_time and inputEndTime < slots.start_time. So, I want to set a variable such as const overlappedSlots = // and get the output of that variable as (console.log(overlappedSlots)):

[{
  start_time: "10:30",
  end_time: "11:00"
}]

But, I can't get this output by writing this function:

const inputStartTime = '10:50';
const inputEndTime = '11:20';

const slots = [
    {
    start_time: '10:30',
    end_time: '11:00'
  },
  {
    start_time: '11:30',
    end_time: '12:00'
  }
]

const overlappedSlots = slots.filter(slot => !slot.end_time < inputStartTime || !slot.start_time > inputEndTime);
console.log(overlappedSlots)

What I was doing wrong there?

CodePudding user response:

The error is when you use ! without parenthesis

const inputStartTime = '10:50';
const inputEndTime = '11:20';

const slots = [{
    start_time: '10:30',
    end_time: '11:00',
  },
  {
    start_time: '11:30',
    end_time: '12:00',
  },
];

const overlappedSlots = slots.filter(
  (slot) => !(slot.end_time < inputStartTime) || !(slot.start_time > inputEndTime)
);
console.log(overlappedSlots);

CodePudding user response:

the problem with your code remains with ! Try this :

const overlappedSlots = slots.filter(slot => !(slot.end_time < inputStartTime) || !(slot.start_time > inputEndTime));

    console.log("over" overlappedSlots);
  • Related