Class: Basketball::Season::Record

Inherits:
Entity
  • Object
show all
Defined in:
lib/basketball/season/record.rb

Overview

Represents a team within a Standings object. Each Record is comprised of Detail instances which are the game results in the perspective of a single Team.

Defined Under Namespace

Classes: DetailAlreadyAddedError, OpponentNotFoundError

Instance Attribute Summary

Attributes inherited from Entity

#id

Instance Method Summary collapse

Methods inherited from Entity

#==, #comparable_id, #hash

Constructor Details

#initialize(id:, details: []) ⇒ Record



11
12
13
14
15
16
17
18
19
# File 'lib/basketball/season/record.rb', line 11

def initialize(id:, details: [])
  super(id)

  @details_by_date = {}

  details.each { |detail| add!(detail) }

  freeze
end

Instance Method Details

#<=>(other) ⇒ Object



63
64
65
# File 'lib/basketball/season/record.rb', line 63

def <=>(other)
  [win_count, win_percentage] <=> [other.win_count, other.win_percentage]
end

#accept!(result) ⇒ Object



21
22
23
24
25
# File 'lib/basketball/season/record.rb', line 21

def accept!(result)
  detail = result_to_detail(result)

  add!(detail)
end

#add!(detail) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/basketball/season/record.rb', line 67

def add!(detail)
  raise DetailAlreadyAddedError, "#{detail} already added for date" if detail_for(detail.date)

  details_by_date[detail.date] = detail

  self
end

#detail_for(date) ⇒ Object



27
28
29
# File 'lib/basketball/season/record.rb', line 27

def detail_for(date)
  details_by_date[date]
end

#detailsObject



31
32
33
# File 'lib/basketball/season/record.rb', line 31

def details
  details_by_date.values
end

#game_count(opponent_type) ⇒ Object



47
48
49
# File 'lib/basketball/season/record.rb', line 47

def game_count(opponent_type)
  details_for(opponent_type).length
end

#loss_count(opponent_type = nil) ⇒ Object



55
56
57
# File 'lib/basketball/season/record.rb', line 55

def loss_count(opponent_type = nil)
  details_for(opponent_type).count(&:loss?)
end

#to_sObject



59
60
61
# File 'lib/basketball/season/record.rb', line 59

def to_s
  "[#{super}] #{win_count}-#{loss_count} (#{win_percentage_display})"
end

#win_count(opponent_type = nil) ⇒ Object



51
52
53
# File 'lib/basketball/season/record.rb', line 51

def win_count(opponent_type = nil)
  details_for(opponent_type).count(&:win?)
end

#win_percentage(opponent_type = nil) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/basketball/season/record.rb', line 35

def win_percentage(opponent_type = nil)
  game_count = game_count(opponent_type)

  return 0 unless game_count.positive?

  (win_count(opponent_type).to_f / game_count).round(3)
end

#win_percentage_display(opponent_type = nil) ⇒ Object



43
44
45
# File 'lib/basketball/season/record.rb', line 43

def win_percentage_display(opponent_type = nil)
  format('%.3f', win_percentage(opponent_type))
end