Sha256: a23b68d596aee72eba2369f341f0bbb9edb7f9dfa594790421d3aa5c1f691c24

Contents?: true

Size: 998 Bytes

Versions: 1

Compression:

Stored size: 998 Bytes

Contents

module MemoryProfiler
  module TopN
    # Efficient mechanism for finding top_n entries in a list
    # optional block can specify custom element and weight
    def top_n(max = 10)

      sorted =
        if block_given?
          self.map { |row|
            yield(row)
          }
        else
          self.dup
        end

      sorted.sort!

      found = []

      last = sorted[0]
      count = 0
      lowest_count = 0

      sorted << nil

      sorted.each do |row|

        current_item, current_count = row

        unless current_item == last
          if count > lowest_count
            found << {data: last, count: count}
          end

          if found.length > max
            found.sort!{|x,y| x[:count] <=> y[:count] }
            found.delete_at(0)
            lowest_count = found[0][:count]
          end

          count = 0
          last = current_item
        end

        count += (current_count || 1) unless row.nil?
      end

      found.reverse
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
memory_profiler-0.0.1 lib/memory_profiler/top_n.rb