Sha256: 024176078d129517a8a5245c81291a6e4e0a1ba949134ea70a542127dc8576c3

Contents?: true

Size: 1.15 KB

Versions: 46

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Don't omit the accumulator when calling `next` in a `reduce` block.
      #
      # @example
      #
      #   # bad
      #
      #   result = (1..4).reduce(0) do |acc, i|
      #     next if i.odd?
      #     acc + i
      #   end
      #
      # @example
      #
      #   # good
      #
      #   result = (1..4).reduce(0) do |acc, i|
      #     next acc if i.odd?
      #     acc + i
      #   end
      class NextWithoutAccumulator < Cop
        MSG = 'Use `next` with an accumulator argument in a `reduce`.'

        def_node_matcher :on_body_of_reduce, <<~PATTERN
          (block (send _recv {:reduce :inject} !sym) _blockargs $(begin ...))
        PATTERN

        def on_block(node)
          on_body_of_reduce(node) do |body|
            void_next = body.each_node(:next).find do |n|
              n.children.empty? && parent_block_node(n) == node
            end

            add_offense(void_next) if void_next
          end
        end

        private

        def parent_block_node(node)
          node.each_ancestor(:block).first
        end
      end
    end
  end
end

Version data entries

46 entries across 35 versions & 5 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.88.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.87.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.87.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.86.0 lib/rubocop/cop/lint/next_without_accumulator.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/lint/next_without_accumulator.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/lint/next_without_accumulator.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.85.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.85.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.84.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.83.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.82.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.81.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.80.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.80.0 lib/rubocop/cop/lint/next_without_accumulator.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/next_without_accumulator.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/next_without_accumulator.rb