Implement sorting correctly with <=> operator

This commit is contained in:
Daniel Schädler 2024-04-07 18:07:55 +02:00
parent 86651169e9
commit 1084d836c1
3 changed files with 15 additions and 18 deletions

View File

@ -7,4 +7,17 @@ class GroupScore < ApplicationRecord
def difference_in_points
scored_points - received_points
end
def <=>(other)
point_comparison = [-group_points, -difference_in_points, -scored_points] <=> [-other.group_points, -other.difference_in_points, -other.scored_points]
p point_comparison, team.name, other.team.name
if point_comparison.zero?
comparison_match = group.matches.find do |match|
match.match_scores.any? { |match_score| match_score.team == team }
end
comparison_match.scored_points_of(team) <=> comparison_match.scored_points_of(other.team)
else
point_comparison
end
end
end

View File

@ -7,12 +7,6 @@ class GroupSerializer < ApplicationSerializer
has_many :matches
def group_scores
sorted_group_scores = object.group_scores.sort_by do |x|
# sort sorts from smallest to largest, therefore we need to negate the values
[
-x.group_points, -(x.scored_points - x.received_points), -x.scored_points
]
end
sorted_group_scores.map { |group_score| GroupScoreSerializer.new(group_score) }
object.group_scores.sort.map { |group_score| GroupScoreSerializer.new(group_score) }
end
end

View File

@ -93,17 +93,7 @@ class GroupStageService
# @param group Group the group to get the teams from
# @return [Array] of teams
def teams_sorted_by_group_scores(group)
group.teams.sort do |a, b|
group_score_a = group.group_scores.find_by(team: a)
group_score_b = group.group_scores.find_by(team: b)
[group_score_b.group_points,
group_score_b.difference_in_points,
group_score_b.scored_points] <=>
[group_score_a.group_points,
group_score_a.difference_in_points,
group_score_a.scored_points]
end
group.group_scores.sort.map(&:team)
end
# Returns all teams advancing to playoff stage from given group stage