Skip to content

Commit

Permalink
I think we could tweak your algorithm a bit so that a course that occ…
Browse files Browse the repository at this point in the history
…urs several days a week, always at the same time would always be "grouped" according to the time first : Mon, Tue, Thu 10:00 - 12:00 (maybe put a check to see it all times are equal at the start of the method, and then if the check fails, the behavior you've proposed is perfect).
  • Loading branch information
rm-yakovenko committed Apr 4, 2022
1 parent 0f66bff commit 87b9d09
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 35 deletions.
40 changes: 6 additions & 34 deletions app/Models/Course.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,40 +308,12 @@ public function getCourseTimesAttribute()
}

$courseTimes = $courseTimes->sortBy('day');
foreach ($courseTimes->groupBy('timeString') as $groupedCourseTimes) {
$currentSeq = [];
foreach ($groupedCourseTimes as $courseTime) {
$prevCourseTime = end($currentSeq);
if ($prevCourseTime && ($courseTime->day - $prevCourseTime->day) !== 1) {
$currentSeq = [];
}
$currentSeq[] = $courseTime;
$courseTime->firstOfSeq = reset($currentSeq);
}
}

$groups = $courseTimes->groupBy(fn (CourseTime $courseTime) => $courseTime->firstOfSeq->id)
->groupBy(fn (Collection $seqGroup) => $seqGroup->count() > 1 ? 'multi_days' : 'multi_times');

$result = [];

// Instead of showing this:
// Mon 9:00 - 5:00 | Tue 9:00 - 5:00 | Wed 9:00 - 5:00 | Thu 9:00 - 5:00 | Fri 9:00 - 5:00
// we could show:
// Mon - Fri 9:00 - 5:00
foreach (collect($groups->get('multi_days', [])) as $group) {
$firstDay = $group->first();
$lastDay = $group->last();
$result[] = "{$firstDay->dayString} - {$lastDay->dayString} {$firstDay->timeString}";
}

// Mon 10:00 AM - 11:00 AM / 11:30 AM - 12:45 PM
foreach (collect($groups->get('multi_times', []))->flatten()->groupBy('day') as $group) {
$firstDay = $group->first();
$result[] = "{$firstDay->dayString} {$group->pluck('timeString')->join(' / ')}";
}

return implode(' | ', $result);
$result = $courseTimes->groupBy('timeString')
->map(function (Collection $group) {
$timeString = $group->first()->timeString;
return "{$group->pluck('dayString')->join(', ')} {$timeString}";
});
return $result->join(' | ');
}

public function getCoursePeriodNameAttribute()
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/CourseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public function course_with_sequential_days_is_correctly_parsed()
$courseTimeParsed = $course->course_times;

$this->assertSame(
'Mon - Wed 10:00 AM - 11:00 AM | Fri - Sat 10:00 AM - 11:00 AM | Thu 10:15 AM - 11:00 AM',
'Mon, Tue, Wed, Fri, Sat 10:00 AM - 11:00 AM | Thu 10:15 AM - 11:00 AM',
$courseTimeParsed
);
}
Expand Down

0 comments on commit 87b9d09

Please sign in to comment.