Sha256: 2f888e74171271bf6ffc11c74793ad29e710657c0e011e1c8cf22f9c207a767f

Contents?: true

Size: 1.41 KB

Versions: 15

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for places where Integer#even? or Integer#odd?
      # should have been used.
      #
      # @example
      #
      #   # bad
      #   if x % 2 == 0
      #
      #   # good
      #   if x.even?
      class EvenOdd < Cop
        MSG = 'Replace with `Integer#%s?`.'.freeze

        def_node_matcher :even_odd_candidate?, <<-PATTERN
          (send
            {(send $_ :% (int 2))
             (begin (send $_ :% (int 2)))}
            ${:== :!=}
            (int ${0 1 2}))
        PATTERN

        def on_send(node)
          even_odd_candidate?(node) do |_base_number, method, arg|
            replacement_method = replacement_method(arg, method)
            add_offense(node, :expression, format(MSG, replacement_method))
          end
        end

        def autocorrect(node)
          even_odd_candidate?(node) do |base_number, method, arg|
            replacement_method = replacement_method(arg, method)

            correction = "#{base_number.source}.#{replacement_method}?"
            ->(corrector) { corrector.replace(node.source_range, correction) }
          end
        end

        private

        def replacement_method(arg, method)
          case arg
          when 0
            method == :== ? :even : :odd
          when 1
            method == :== ? :odd : :even
          end
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/even_odd.rb
rubocop-0.50.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.49.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.49.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.48.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.48.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.47.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.47.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.46.0 lib/rubocop/cop/style/even_odd.rb