Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.2 kB
3
Indexable
Never
const array = [
  {
    start: '1:15 PM',
    end: '1:30 PM',
    status: 1,
  },
  {
    start: '1:30 PM',
    end: '1:45 PM',
    status: 1,
  },
  {
    start: '2:15 PM',
    end: '2:30 PM',
    status: 1,
  },
  {
    start: '2:30 PM',
    end: '2:45 PM',
    status: 1,
  },
  {
    start: '2:45 PM',
    end: '3:00 PM',
    status: 1,
  },
  {
    start: '3:00 PM',
    end: '3:15 PM',
    status: 1,
  },
  {
    start: '3:30 PM',
    end: '3:45 PM',
    status: 1,
  },
  {
    start: '3:45 PM',
    end: '4:00 PM',
    status: 1,
  },
  {
    start: '4:00 PM',
    end: '4:15 PM',
    status: 1,
  },
  {
    start: '4:15 PM',
    end: '4:30 PM',
    status: 1,
  },
  {
    start: '4:30 PM',
    end: '4:45 PM',
    status: 1,
  },
];

function combineTimeSlots(
  arr = [
    {
      start: '4:30 PM',
      end: '4:45 PM',
      status: 1,
    },
  ],
  duration = 20
) {
  // assume that array was sorted in ascend and every slot is 15 min
  const slots = duration % 15 === 0 ? duration / 15 : ~~(duration / 15) + 1;
  const n = arr.length;
  let i = 0;
  const res = [];
  while (i < n - slots) {
    let shouldAdd = true;
    for (let j = i; j < i + slots - 1; j++) {
      const slot = arr[j];
      const next = arr[j + 1];
      if (next.start != slot.end) {
        shouldAdd = false;
        i = j + 1;
        break;
      }
    }
    if (shouldAdd) {
      res.push({
        start: arr[i].start,
        end: arr[i + slots - 1].end,
        status: 1,
      });
      i = i + slots;
    }
  }

  return res;
}

const result = combineTimeSlots(array, 45);
// expect
/*
 [
 {
    start: "2:15 PM",
    end: "3:00 PM",
    status: 1
  },
  {
    start: "3:30 PM",
    end: "4:15 PM",
    status: 1
  },

 ]

*/

const result1 = combineTimeSlots(array, 30);

// expect
/*
 [
 {
    start: "1:15 PM",
    end: "1:45 PM",
    status: 1
  },
  {
    start: "2:15 PM",
    end: "2:45 PM",
    status: 1
  },
  {
    start: "2:45 PM",
    end: "3:15 PM",
    status: 1
  },
  // 3:30 - 4:00,
  // 4:00 - 4:30
 ]

*/
const result2 = combineTimeSlots(array, 60);

/*

 */

const result3 = combineTimeSlots(array, 20);

console.log({ result, result1, result2, result3 });