Sha256: 0a7025db16c5fabe0f993a406bc7367bb0f2359ddf95e7d3d4211cfd83bbbb06

Contents?: true

Size: 1.12 KB

Versions: 11

Compression:

Stored size: 1.12 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
      #
      #   # 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`.'.freeze

        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, :expression) if void_next
          end
        end

        private

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

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.46.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.45.0 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.44.1 lib/rubocop/cop/lint/next_without_accumulator.rb
rubocop-0.44.0 lib/rubocop/cop/lint/next_without_accumulator.rb