Class: MarkdownExec::Histogram

Inherits:
Object
  • Object
show all
Defined in:
lib/markdown_exec.rb

Overview

A class that generates a histogram bar in terminal using xterm-256 color codes.

Class Method Summary collapse

Class Method Details

.display(integer_value, min, max, width, inverse: false) ⇒ Object

Generates and prints a histogram bar for a given value within a specified range and width, with an option for inverse display.

Parameters:

  • integer_value (Integer)

    the value to represent in the histogram

  • min (Integer)

    the minimum value of the range

  • max (Integer)

    the maximum value of the range

  • width (Integer)

    the total width of the histogram in characters

  • inverse (Boolean) (defaults to: false)

    whether the histogram is displayed in inverse order (right to left)



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/markdown_exec.rb', line 133

def self.display(integer_value, min, max, width, inverse: false)
  return if max <= min # Ensure the range is valid

  # Normalize the value within the range 0 to 1
  normalized_value = [0, [(integer_value - min).to_f / (max - min), 1].min].max

  # Calculate how many characters should be filled
  filled_length = (normalized_value * width).round

  # # Generate the histogram bar using xterm-256 colors (color code 42 is green)
  # filled_bar = "\e[48;5;42m" + ' ' * filled_length + "\e[0m"
  filled_bar = ('ยค' * filled_length).fg_rgbh_AF_AF_00
  empty_bar = ' ' * (width - filled_length)

  # Determine the order of filled and empty parts based on the inverse flag
  inverse ? (empty_bar + filled_bar) : (filled_bar + empty_bar)
end