Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: initial full cleanup #157

Merged
merged 4 commits into from
Sep 22, 2024

Conversation

cirex-web
Copy link
Collaborator

@cirex-web cirex-web commented Sep 9, 2024

Description

No change in functionality, just a lot of moving code around for a hopefully more readable/debuggable codebase.

Conveniently closes #150 (tests aren't in this PR but I ran them here to make sure)
image

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

  • Test A
  • Test B

Test Configuration:

  • Node.js version:
  • Python version:
  • Desktop/Mobile:
  • OS:
  • Browser:

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Copy link

vercel bot commented Sep 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dining-api ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 20, 2024 9:25pm

@GhostOf0days
Copy link
Member

GhostOf0days commented Sep 9, 2024

Heads up while still in draft.

Some logic in dealing with schedule strings was moved to various locations. Merge interval logic has caused failures on edge cases before. Therefore, please use a version of this block of logic (its complexity is needed for edge cases) rather than moving its logic or keep most of it in one area in this PR, so easier to review and don't accidentally break API. Can refactor in new PR after.

More specifically, this logic is very important:

      const timeInfoType = determineTimeInfoType(timeStr);

      if (
        timeInfoType === TimeInfoType.CLOSED ||
        timeInfoType === TimeInfoType.TWENTYFOURHOURS
      ) {
        const scheduleString = `${dayStr.trim()}, ${timeStr}`;
        addedSchedules.add(scheduleString);
        timeBuilder.addSchedule([dayStr.trim(), dateStr.trim(), timeStr]);
      } else if (timeInfoType === TimeInfoType.TIME) {
        const timeSlots = timeStr.split(/[,;]/).map((slot) => slot.trim());

        // Sort time slots based on opening time
        timeSlots.sort((a, b) => {
          const [aStart, aEnd] = a.split("-").map((time) => time.trim());
          const [bStart, bEnd] = b.split("-").map((time) => time.trim());
          const startComparison = aStart.localeCompare(bStart);
          if (startComparison !== 0) {
            return startComparison;
          }
          return bEnd.localeCompare(aEnd); // Reverse order for end times
        });

        // Merge overlapping, contained, and duplicate time slots
        const mergedTimeSlots = [];
        let prevSlot = null;
        for (const timeSlot of timeSlots) {
          const [start, end] = timeSlot.split("-").map((time) => time.trim());

          if (prevSlot && start === prevSlot.start) {
            // If the current time slot has the same opening time as the previous one
            // Update the previous slot with the later closing time
            if (end > prevSlot.end) {
              prevSlot.end = end;
            }
          } else {
            mergedTimeSlots.push({ start, end });
            prevSlot = { start, end };
          }
        }

        // Format and add merged time slots
        mergedTimeSlots.forEach((slot) => {
          let { start, end } = slot;

          // Handle case where end time is 12:00 AM
          if (/12:00 AM$/i.test(end)) {
            end = end.replace(/12:00 AM$/i, "11:59 PM");
          }

          const scheduleString = `${dayStr.trim()}, ${start} - ${end}`;
          if (!addedSchedules.has(scheduleString)) {
            addedSchedules.add(scheduleString);
            timeBuilder.addSchedule([
              dayStr.trim(),
              dateStr.trim(),
              `${start} - ${end}`,
            ]);
          }
        });
      }
    }

    builder.setTimes(timeBuilder.build());

@cirex-web

This comment was marked as outdated.

@cirex-web
Copy link
Collaborator Author

cirex-web commented Sep 10, 2024

Thanks for pointing that out! I believe that the above functionality has all been shifted to the following two code snippets:

export function sortAndMergeTimeRanges(timeRanges: ITimeRange[]) {
  timeRanges.sort((range1, range2) =>
    compareTimeMoments(range1.start, range2.start)
  );
  const mergedRanges: ITimeRange[] = [];

  for (const timeRange of timeRanges) {
    const lastTimeRange = mergedRanges.length
      ? mergedRanges[mergedRanges.length - 1]
      : undefined;
    if (
      lastTimeRange &&
      compareTimeMoments(lastTimeRange.end, timeRange.start) >= 0
    ) {
      if (compareTimeMoments(timeRange.end, lastTimeRange.end) > 0) {
        lastTimeRange.end = timeRange.end; // join current range with last range
      }
    } else {
      mergedRanges.push(timeRange);
    }
  }
  console.log(timeRanges, mergedRanges);
  return mergedRanges;
}

and

function getTimeRangesFromTimeRow(time: ITimeRowAttributes) {
  if (time.day === undefined) {
    throw new Error("Cannot convert when day is not set");
  }
  const allRanges: ITimeRange[] = [];
  for (const range of time.times ?? []) {
    if (range.end.hour === 0 && range.end.minute === 0) {
      range.end.hour = 23;
      range.end.minute = 59; // roll back from 12AM to 11:59 previous day <- specifically this
    }

    const spillToNextDay =
      range.start.hour * 60 + range.start.minute >
      range.end.hour * 60 + range.end.minute;

    allRanges.push({
      start: {
        day: time.day,
        hour: range.start.hour,
        minute: range.start.minute,
      },
      end: {
        day: spillToNextDay ? getNextDay(time.day) : time.day,
        hour: range.end.hour,
        minute: range.end.minute,
      },
    });
  }
  return allRanges;
}

so rather than filtering by type and sorting before time parsing, we just do it afterwards with the parsed ITimeRanges

This code also passes all edge cases mentioned in a previous issue (the tests are in the other PR - not this one)

@GhostOf0days GhostOf0days merged commit c14762c into ScottyLabs:main Sep 22, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Account for All Edge Cases
2 participants