Skip to content

Commit

Permalink
Add memoized versions of rgb_colors for foreground and background c…
Browse files Browse the repository at this point in the history
…olors.

The changes were made to improve performance by reducing the number of
calculations required to find the nearest color for a given RGB value.
The `rgb_foreground_colors` and `rgb_background_colors` methods only
return colors that match the specified options, which can help reduce
the amount of data that needs to be processed.
  • Loading branch information
flori committed Jul 24, 2024
1 parent 88e60fe commit 9097e8e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
29 changes: 20 additions & 9 deletions lib/term/ansicolor/attribute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,25 @@ def self.get(name)
@__store__[name.to_sym]
end

def self.rgb_colors(options = {}, &block)
colors = attributes.select(&:rgb_color?)
if options.key?(:gray) && !options[:gray]
colors = colors.reject(&:gray?)
class << self
memoize method:
def rgb_colors(options = {}, &block)
colors = attributes.select(&:rgb_color?)
if options.key?(:gray) && !options[:gray]
colors = colors.reject(&:gray?)
end
colors.each(&block)
end

memoize method:
def rgb_foreground_colors(options = {}, &block)
rgb_colors(options).reject(&:background?).each(&block)
end

memoize method:
def rgb_background_colors(options = {}, &block)
rgb_colors(options).select(&:background?).each(&block)
end
colors.each(&block)
end

def self.named_attributes(&block)
Expand All @@ -63,14 +76,12 @@ def self.named_attributes(&block)

def self.nearest_rgb_color(color, options = {})
rgb = RGBTriple[color]
colors = rgb_colors(options)
colors.reject(&:background?).min_by { |c| c.distance_to(rgb, options) }
rgb_foreground_colors(options).min_by { |c| c.distance_to(rgb, options) }
end

def self.nearest_rgb_on_color(color, options = {})
rgb = RGBTriple[color]
colors = rgb_colors(options)
colors.select(&:background?).min_by { |c| c.distance_to(rgb, options) }
rgb_background_colors(options).min_by { |c| c.distance_to(rgb, options) }
end

def self.true_color(color, options = {})
Expand Down
2 changes: 1 addition & 1 deletion lib/term/ansicolor/attribute/color256.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class Color256
Attribute.set :on_color4, 4, html: '#000080', background: true
Attribute.set :on_color5, 5, html: '#800080', background: true
Attribute.set :on_color6, 6, html: '#008080', background: true
Attribute.set :on_color7, 7, html: '#c0c0c0'
Attribute.set :on_color7, 7, html: '#c0c0c0', background: true

Attribute.set :on_color8, 8, html: '#808080', background: true
Attribute.set :on_color9, 9, html: '#ff0000', background: true
Expand Down

0 comments on commit 9097e8e

Please sign in to comment.