Module: YouPlot::Backends::Processing

Defined in:
lib/youplot/backends/processing.rb

Class Method Summary collapse

Class Method Details

.count_values(arr, tally: true, reverse: false) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/youplot/backends/processing.rb', line 9

def count_values(arr, tally: true, reverse: false)
  # tally was added in Ruby 2.7
  result = \
    if tally && Enumerable.method_defined?(:tally)
      arr.tally
    else
      # value_counts Enumerable::Statistics
      arr.value_counts(dropna: false)
    end

  # sorting
  result = result.sort do |a, b|
    # compare values
    r = b[1] <=> a[1]
    # If the values are the same, compare by name
    r = a[0] <=> b[0] if r.zero?
    r
  end

  # --reverse option
  result.reverse! if reverse

  # prepare for barplot
  result.transpose
end