Skip to content

Instantly share code, notes, and snippets.

@aokolish
Created November 3, 2017 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aokolish/15c6074de60ab39af007f7ff0916e2d7 to your computer and use it in GitHub Desktop.
Save aokolish/15c6074de60ab39af007f7ff0916e2d7 to your computer and use it in GitHub Desktop.
closest web safe color...v2
WEB_SAFE_NUMBERS = [
0, # 00
51, # 33
102, # 66
153, # 99
204, # cc
255 # ff
]
def closest_web_safe_color(string)
string.gsub!('#', '')
string = double_chars_if_needed(string)
output = string.downcase.scan(/.{2}/).inject("#") do |memo, chunk|
base_ten = chunk.to_i(16)
closest_web_safe = WEB_SAFE_NUMBERS.min_by { |num| (base_ten - num).abs }
closest_web_safe_hex = closest_web_safe.to_s(16).ljust(2, '0')
memo << closest_web_safe_hex
end
if string.upcase == string
output.upcase
else
output
end
end
def double_chars_if_needed(string)
if string.length < 6
string = string.chars.map do |char|
char * 2
end.join
else
string
end
end
require 'minitest/autorun'
class TestMoveZeroes < Minitest::Test
def test_it_works
assert_equal '#993300', closest_web_safe_color('#ae3312')
assert_equal '#993300', closest_web_safe_color('#993300')
assert_equal '#cc3300', closest_web_safe_color('de3214')
assert_equal '#CC0033', closest_web_safe_color('#D40123')
assert_equal '#333333', closest_web_safe_color('#323')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment