From 61578d9fb2a5d62d68b955d628d30cfc760821d7 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 6 Sep 2020 02:56:46 +0900 Subject: [PATCH] [Fix #165] Fix a false positive for `Performance/Sum` Fixes #165. This PR fixes a false positive for `Performance/Sum` when using initial value argument is a variable. --- CHANGELOG.md | 1 + lib/rubocop/cop/performance/sum.rb | 2 +- spec/rubocop/cop/performance/sum_spec.rb | 33 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 075bdb6470..10af6840ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/rubocop/cop/performance/sum.rb b/lib/rubocop/cop/performance/sum.rb index a1bf307d0c..e3d66c9213 100644 --- a/lib/rubocop/cop/performance/sum.rb +++ b/lib/rubocop/cop/performance/sum.rb @@ -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 diff --git a/spec/rubocop/cop/performance/sum_spec.rb b/spec/rubocop/cop/performance/sum_spec.rb index b0b10f74da..edaf3737c1 100644 --- a/spec/rubocop/cop/performance/sum_spec.rb +++ b/spec/rubocop/cop/performance/sum_spec.rb @@ -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}(:+)