Skip to content

Instantly share code, notes, and snippets.

@QuotableWater7
Created July 26, 2016 15:11
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 QuotableWater7/99390af9bfb68218ec4bbce306dec979 to your computer and use it in GitHub Desktop.
Save QuotableWater7/99390af9bfb68218ec4bbce306dec979 to your computer and use it in GitHub Desktop.
Websafe Color Converter
class WebsafeColorConverter
class InvalidHexError < StandardError; end;
def call(hex_color)
raise InvalidHexError unless valid_hex?(hex_color)
return hex_color if valid_3_char_hex?(hex_color)
return websafe_hex_color(hex_color) if valid_6_char_hex?(hex_color)
# hex_values = hex_color.split('#').last
# '#' + hex_values.chars.each_slice(2).flat_map do |value|
# second_hex_value = value.last
# round
# [value.first, value.first]
# end.join
end
private
def valid_hex_color?(hex_color)
hex_color =~ /\A#?(?:[0-9A-F]{3}){1,2}\z/i
end
def websafe_hex_color(hex_color)
value_portion = hex_color.each_slice(2).flat_map do |hex_string|
closest_websafe_number(hex_string)
end
"##{value_portion}"
end
# F4 => EE
def closest_websafe_number(hex_string)
# convert F4 to integer
# absolute value trick to get closest integer
# convert integer to hex
end
end
# F0 => EE FF
# FFF
require 'rspec'
require_relative '../websafe_color_converter'
RSpec.describe WebsafeColorConverter do
let(:converter) { described_class.new }
describe '#call' do
it 'converts to a websafe color' do
expect(converter.call('#ffbc40')).to eq '#ffbb44'
end
it 'returns same value if it is already websafe' do
expect(converter.call('#FFFFFF')).to eq '#FFFFFF'
end
it 'raises exception when hex color that is too long is passed in' do
expect { converter.call('#12Af567') }.to raise_error(WebsafeColorConverter::InvalidHexError)
end
it 'raises exception when hex color that is too short is passed in' do
expect { converter.call('#12Af5') }.to raise_error(WebsafeColorConverter::InvalidHexError)
end
it 'works when no # provided' do
expect(converter.call('12Af51')).to eq '#11AA55'
end
it 'works when hex value provided is only 3 digits' do
expect(converter.call('12A')).to eq '#1122AA'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment