Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions lib/fbe/award.rb
Original file line number Diff line number Diff line change
Expand Up @@ -396,19 +396,24 @@ def points
# bill.line(25, "for documentation")
# bill.greeting #=> "You've earned +75 points for this: +50 for code review; +25 for documentation. "
def greeting
items = @lines.map { |l| "#{format('%+d', whole(l[:v]))} #{l[:t]}" }
case items.size
when 0
"You've earned nothing. "
when 1
"You've earned #{format('%+d', points)} points. "
else
"You've earned #{format('%+d', points)} points for this: #{items.join('; ')}. "
end
return "You've earned nothing. " if @lines.empty?
items = shares.filter_map { |l| "#{format('%+d', l[:v])} #{l[:t]}" unless l[:v].zero? }
return "You've earned #{format('%+d', points)} points. " if @lines.size == 1 || items.empty?
"You've earned #{format('%+d', points)} points for this: #{items.join('; ')}. "
end

private

# Splits the rounded total between the lines, by the largest remainder.
#
# @return [Array<Hash>] Lines with whole values that add up to +points+
def shares
parts = @lines.map { |l| { v: Float(l[:v]).floor, t: l[:t], r: Float(l[:v]) - Float(l[:v]).floor } }
extra = points - parts.sum { |l| l[:v] }
parts.sort_by.with_index { |l, i| [-l[:r], i] }.first(extra).each { |l| l[:v] += 1 }
parts
end

# Rounds one line value the way the total is rounded.
#
# @param [Float, Integer] value The value of one line
Expand Down
11 changes: 11 additions & 0 deletions test/fbe/test_award.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ def test_some_terms
end
end

def test_greeting_lines_add_up_to_the_total
{
'(award (give 0.4 "a") (give 0.4 "b") (give 0.4 "c"))' => "You've earned +1 points for this: +1 a. ",
'(award (give 0.5 "a") (give 0.5 "b"))' => "You've earned +1 points for this: +1 a. ",
'(award (give -3.5 "a") (give 1 "b"))' => "You've earned -3 points for this: -4 a; +1 b. ",
'(award (give 0.2 "a") (give 0.2 "b"))' => "You've earned +0 points. "
}.each do |q, v|
assert_equal(v, Fbe::Award.new(q).bill.greeting, q)
end
end

def test_some_greetings
{
'(award (give (times 7 0.25 "fun")))' => 'You\'ve earned +2 points. ',
Expand Down
Loading