Sha256: 97c2501a6099f3e806ff0c5bd4c91ecbbb0c71d05d135426d7aa16b343b1fbce

Contents?: true

Size: 1.65 KB

Versions: 14

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop is used to identify usages of `count` on an
      # `Array` and `Hash` and change them to `size`.
      #
      # @example
      #   # bad
      #   [1, 2, 3].count
      #
      #   # bad
      #   {a: 1, b: 2, c: 3}.count
      #
      #   # good
      #   [1, 2, 3].size
      #
      #   # good
      #   {a: 1, b: 2, c: 3}.size
      #
      #   # good
      #   [1, 2, 3].count { |e| e > 2 }
      # TODO: Add advanced detection of variables that could
      # have been assigned to an array or a hash.
      class Size < Cop
        MSG = 'Use `size` instead of `count`.'.freeze

        def on_send(node)
          return unless eligible_node?(node)

          add_offense(node, location: :selector)
        end

        def autocorrect(node)
          ->(corrector) { corrector.replace(node.loc.selector, 'size') }
        end

        private

        def eligible_node?(node)
          return false unless node.method?(:count) && !node.arguments?

          eligible_receiver?(node.receiver) && !allowed_parent?(node.parent)
        end

        def eligible_receiver?(node)
          return false unless node

          array?(node) || hash?(node)
        end

        def allowed_parent?(node)
          node && node.block_type?
        end

        def array?(node)
          _, constant = *node.receiver

          node.array_type? || constant == :Array || node.method_name == :to_a
        end

        def hash?(node)
          _, constant = *node.receiver

          node.hash_type? || constant == :Hash || node.method_name == :to_h
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 3 rubygems

Version Path
rubocop-0.58.2 lib/rubocop/cop/performance/size.rb
rubocop-performance-0.0.0 lib/rubocop/cop/performance/size.rb
rubocop-0.58.1 lib/rubocop/cop/performance/size.rb
rubocop-0.58.0 lib/rubocop/cop/performance/size.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/performance/size.rb
rubocop-0.57.2 lib/rubocop/cop/performance/size.rb
rubocop-0.57.1 lib/rubocop/cop/performance/size.rb
rubocop-0.57.0 lib/rubocop/cop/performance/size.rb
rubocop-0.56.0 lib/rubocop/cop/performance/size.rb
rubocop-0.55.0 lib/rubocop/cop/performance/size.rb
rubocop-0.54.0 lib/rubocop/cop/performance/size.rb
rubocop-0.53.0 lib/rubocop/cop/performance/size.rb
rubocop-0.52.1 lib/rubocop/cop/performance/size.rb
rubocop-0.52.0 lib/rubocop/cop/performance/size.rb