Timeline Builder Algorithm

JS
S
JavaScript

Simple row builder algorithm

1function timeToSlot(timeString) {
2  const [hours, minutes] = timeString.split(':').map(Number);
3  const adjustedHours = (hours + 18) % 24; // Shift the starting time to 06:00
4  return adjustedHours * 12 + Math.floor(minutes / 5);
5}
6
7function slotToTime(slot) {
8  const adjustedHours = (Math.floor(slot / 12) + 6) % 24; // Shift the starting time back to 00:00
9  const minutes = (slot % 12) * 5;
10  return `${adjustedHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
11}
12
13function dataRows(rawData) {
14  const totalSlots = 288;
15  const result = [];
16  let currentSlot = 0;
17
18  rawData.forEach((item) => {
19    const startSlot = timeToSlot(item.start);
20    const endSlot = Math.max(timeToSlot(item.end), startSlot + 1); // Ensure minimum colSpan is 15
21
22    if (startSlot > currentSlot) {
23      result.push({
24        type: 'gap',
25        colSpan: (startSlot - currentSlot) * 15,
26        start: slotToTime(currentSlot),
27        end: item.start,
28        cellPosition: currentSlot + 1,
29      });
30    }
31
32    result.push({
33      type: item.type,
34      colSpan: (endSlot - startSlot) * 15,
35      start: item.start,
36      end: item.end,
37      cellPosition: startSlot + 1,
38    });
39
40    currentSlot = endSlot;
41  });
42
43  if (currentSlot < totalSlots) {
44    result.push({
45      type: 'gap',
46      colSpan: (totalSlots - currentSlot) * 15,
47      start: slotToTime(currentSlot),
48      end: '05:59',
49      cellPosition: currentSlot + 1,
50    });
51  }
52
53  return result;
54}
55
56const rawData = [
57  { start: '09:43', end: '11:19', type: '100048 COMPLETED' },
58  { start: '11:04', end: '14:45', type: '100052 COMPLETED' },
59];
60
61console.table(dataRows(rawData));
62

Created on 4/26/2023