eargollo / soccer

0 stars 0 forks source link

Refactor probability #5

Open eargollo opened 10 months ago

eargollo commented 10 months ago
          You can also avoid writing this hash all together if you pull some methods into your model:
# match.rb

  def probability # rubocop:disable Metrics/AbcSize
    return @probability if defined?(@probability)

    @probability = [PROB_WIN, PROB_DRAW, PROB_LOSS]
    return @probability if team_away.nil? || team_home.nil?

    prob_home = [PROB_WIN, PROB_DRAW, PROB_LOSS]
    if team_home.home_matches.finished.count.positive?
      prob_home[0] = team_home.home_matches.won_home.count.to_f / team_home.home_matches.finished.count
      prob_home[1] = team_home.home_matches.draw.count.to_f / team_home.home_matches.finished.count
      prob_home[2] = team_home.home_matches.won_away.count.to_f / team_home.home_matches.finished.count
    end

    prob_away = [PROB_LOSS, PROB_DRAW, PROB_WIN]
    if team_away.away_matches.finished.count.positive?
      prob_away[0] = team_away.away_matches.won_home.count.to_f / team_away.away_matches.finished.count
      prob_away[1] = team_away.away_matches.draw.count.to_f / team_away.away_matches.finished.count
      prob_away[2] = team_away.away_matches.won_away.count.to_f / team_away.away_matches.finished.count
    end

    @probability = [
      (PROB_WIN + (4.5 * prob_home[0]) + (4.5 * prob_away[0])) / 10,
      (PROB_DRAW + (4.5 * prob_home[1]) + (4.5 * prob_away[1])) / 10,
      (PROB_LOSS + (4.5 * prob_home[2]) + (4.5 * prob_away[2])) / 10
    ]
  end

  def probability_of_win
    probability[0]
  end

  def probability_of_draw
    probability[1]
  end

  def probability_of_loss
    probability[2]
  end

  def probability_of_not_losing
    probability_of_win + probability_of_draw
  end

If you do this, then you can simply iterate over the Match objects and call things like match.probability_of_not_losing and match.probability_of_win to make the method more readable, and cut down on the AbcSize + Complexity metrics.

_Originally posted by @csalvato in https://github.com/eargollo/soccer/pull/3#discussion_r1372652959_