From 9097e8e4bb0957fb6e9aa43fff93065df0e79f45 Mon Sep 17 00:00:00 2001 From: Florian Frank Date: Wed, 24 Jul 2024 02:04:26 +0200 Subject: [PATCH] Add memoized versions of `rgb_colors` for foreground and background colors. 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. --- lib/term/ansicolor/attribute.rb | 29 ++++++++++++++++-------- lib/term/ansicolor/attribute/color256.rb | 2 +- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/lib/term/ansicolor/attribute.rb b/lib/term/ansicolor/attribute.rb index 01c7536..2eb0e56 100644 --- a/lib/term/ansicolor/attribute.rb +++ b/lib/term/ansicolor/attribute.rb @@ -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) @@ -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 = {}) diff --git a/lib/term/ansicolor/attribute/color256.rb b/lib/term/ansicolor/attribute/color256.rb index f40a9c0..351f587 100644 --- a/lib/term/ansicolor/attribute/color256.rb +++ b/lib/term/ansicolor/attribute/color256.rb @@ -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