Skip to content

Commit

Permalink
[Fix #165] Fix a false positive for Performance/Sum
Browse files Browse the repository at this point in the history
Fixes #165.

This PR fixes a false positive for `Performance/Sum`
when using initial value argument is a variable.
  • Loading branch information
koic committed Sep 5, 2020
1 parent 5da259b commit 61578d9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#164](https://github.com/rubocop-hq/rubocop-performance/pull/164): Fix an error for `Performance/CollectionLiteralInLoop` when a method from `Enumerable` is called with no receiver. ([@eugeneius][])
* [#165](https://github.com/rubocop-hq/rubocop-performance/issues/165): Fix a false positive for `Performance/Sum` when using initial value argument is a variable. ([@koic][])

## 1.8.0 (2020-09-04)

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/performance/sum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def build_good_method(init)

unless init.empty?
init = init.first
good_method += "(#{init.source})" if init.source.to_i != 0
good_method += "(#{init.source})" unless init.int_type? && init.value.zero?
end
good_method
end
Expand Down
33 changes: 33 additions & 0 deletions spec/rubocop/cop/performance/sum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,39 @@
RUBY
end

it "registers an offense and corrects when using `array.#{method}(0, :+)`" do
expect_offense(<<~RUBY, method: method)
array.#{method}(0, :+)
^{method}^^^^^^^ Use `sum` instead of `#{method}(0, :+)`.
RUBY

expect_correction(<<~RUBY)
array.sum
RUBY
end

it "registers an offense and corrects when using `array.#{method}(0.0, :+)`" do
expect_offense(<<~RUBY, method: method)
array.#{method}(0.0, :+)
^{method}^^^^^^^^^ Use `sum(0.0)` instead of `#{method}(0.0, :+)`.
RUBY

expect_correction(<<~RUBY)
array.sum(0.0)
RUBY
end

it "registers an offense and corrects when using `array.#{method}(init, :+)`" do
expect_offense(<<~RUBY, method: method)
array.#{method}(init, :+)
^{method}^^^^^^^^^^ Use `sum(init)` instead of `#{method}(init, :+)`.
RUBY

expect_correction(<<~RUBY)
array.sum(init)
RUBY
end

it 'does not autocorrect when initial value is not provided' do
expect_offense(<<~RUBY, method: method)
array.#{method}(:+)
Expand Down

0 comments on commit 61578d9

Please sign in to comment.