Skip to content

Instantly share code, notes, and snippets.

@endemic
Created September 28, 2016 13:56
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 endemic/29df99bf6205b3b44db46854d17083c4 to your computer and use it in GitHub Desktop.
Save endemic/29df99bf6205b3b44db46854d17083c4 to your computer and use it in GitHub Desktop.
Coding challenge to convert a 6-digit hex color code to its nearest "web safe" equivalent
/**
* Given an input of a 6-character hex color code, we need to output a "web-safe"
* representation of that same code.
*/
'use strict';
let assert = (one, two) => {
if (one === two) {
console.info(`Success! ${one} is equal to ${two}!`);
} else {
console.error(`Failbomb! ${one} is _NOT_ equal to ${two}!`);
}
};
const convert = hex_input => {
let valid_input = validate(hex_input);
let rgb_values = hex_to_decimal(valid_input);
let rounded_rgb_values = [];
let rounded_hex_rgb_values = [];
rgb_values.forEach(i => {
// How to round to multiple of 51?
let safe_value = closest_multiple_of_51(i);
rounded_rgb_values.push(safe_value);
});
// convert back to hex
rounded_rgb_values.forEach(i => {
rounded_hex_rgb_values.push(i.toString(16));
});
return `#${rounded_hex_rgb_values.join('')}`;
};
const validate = string => {
// TODO: normalize valid 3 character color strings to 6 characters; e.g. #333 => #333333
// TODO: actual work here, ensure a 6-character hex string
return string;
};
const hex_to_decimal = hex_input => {
// hex_input: #000000
let red_hex = hex_input.substr(1, 2);
let green_hex = hex_input.substr(3, 2);
let blue_hex = hex_input.substr(5, 2);
let red_decimal = parseInt(red_hex, 16);
let green_decimal = parseInt(green_hex, 16);
let blue_decimal = parseInt(blue_hex, 16);
return [red_decimal, green_decimal, blue_decimal];
};
const closest_multiple_of_51 = number => {
let remainder = number % 51;
if (remainder === 0) {
return number;
}
if (remainder > 51 / 2) {
number += (51 - remainder);
} else {
number -= remainder;
}
return number;
};
assert(closest_multiple_of_51(0), 0);
assert(closest_multiple_of_51(255), 255);
assert(closest_multiple_of_51(45), 51);
assert(closest_multiple_of_51(65), 51);
assert(closest_multiple_of_51(111), 102);
assert(closest_multiple_of_51(160), 153);
assert(closest_multiple_of_51(90), 102);
assert(closest_multiple_of_51(24), 0);
assert(closest_multiple_of_51(25), 0);
assert(closest_multiple_of_51(26), 51);
let results = hex_to_decimal('#000033');
assert(results[0], 0);
assert(results[1], 0);
assert(results[2], 51);
results = hex_to_decimal('#ae3312');
assert(results[0], 174);
assert(results[1], 51);
assert(results[2], 18);
assert(convert('#000044'), '#000033');
assert(convert('#ae3312'), '#993300');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment