Created
November 3, 2017 20:35
-
-
Save aokolish/703335a28489eb3e7adb7fdd7c09a0c7 to your computer and use it in GitHub Desktop.
closest web safe color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WEB_SAFE_NUMBERS = [ | |
0, # 00 | |
51, # 33 | |
102, # 66 | |
153, # 99 | |
204, # cc | |
255 # ff | |
] | |
def closest_web_safe_color(string) | |
new_string = "#" | |
string.gsub("#", "").downcase.scan(/.{2}/).each do |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) | |
if closest_web_safe_hex == '0' | |
closest_web_safe_hex *= 2 | |
end | |
new_string << closest_web_safe_hex | |
end | |
new_string | |
end | |
require 'minitest/autorun' | |
class TestMoveZeroes < Minitest::Test | |
def test_it_works | |
assert_equal '#993300', closest_web_safe_color('#ae3312') | |
end | |
end | |
__END__ | |
"ae".to_i(16) => base 10 number | |
170.to_s(16) => hex string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment