diff --git a/lib/youplot/backends/processing.rb b/lib/youplot/backends/processing.rb new file mode 100644 index 0000000..9b7bcb2 --- /dev/null +++ b/lib/youplot/backends/processing.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module YouPlot + # plotting functions. + module Backends + module Processing + module_function + + def count_values(arr) + # tally was added in Ruby 2.7 + if Enumerable.method_defined? :tally + arr.tally + else + # https://github.com/marcandre/backports + arr.each_with_object(Hash.new(0)) { |item, res| res[item] += 1 } + .tap { |h| h.default = nil } + end + .sort { |a, b| a[1] <=> b[1] } + .reverse + .transpose + end + end + end +end diff --git a/lib/youplot/backends/unicode_plot_backend.rb b/lib/youplot/backends/unicode_plot_backend.rb index 9ead9b2..16ace0b 100644 --- a/lib/youplot/backends/unicode_plot_backend.rb +++ b/lib/youplot/backends/unicode_plot_backend.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative 'processing' require 'unicode_plot' module YouPlot @@ -13,7 +14,7 @@ module YouPlot series = data.series # `uplot count` if count - series = Preprocessing.count_values(series[0]) + series = Processing.count_values(series[0]) params.title = headers[0] if headers end if series.size == 1 diff --git a/test/youplot/backends/processing_test.rb b/test/youplot/backends/processing_test.rb new file mode 100644 index 0000000..94275f8 --- /dev/null +++ b/test/youplot/backends/processing_test.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +require_relative '../../test_helper' + +class YouPlotCommandTest < Test::Unit::TestCase + test :count_values do + @m = YouPlot::Backends::Processing + assert_equal([%i[a b c], [3, 2, 1]], @m.count_values(%i[a a a b b c])) + assert_equal([%i[c b a], [3, 2, 1]], @m.count_values(%i[a b b c c c])) + end +end