Sha256: 6319582ffa437b06695759cf96fc231ac78da738a93a4389faaf39f6431fd1d5

Contents?: true

Size: 1.15 KB

Versions: 34

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 < Base
        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

34 entries across 34 versions & 3 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.10.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.9.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.9.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.8.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.8.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.7.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.6.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.6.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.5.2 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.5.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.5.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.4.2 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.4.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-1.4.0 lib/rubocop/cop/lint/next_without_accumulator.rb