Skip to content

Instantly share code, notes, and snippets.

@AlexJuarez
Created November 11, 2019 19:39
Show Gist options
  • Save AlexJuarez/c338afb427c2cf5efb8f058c2c4a8229 to your computer and use it in GitHub Desktop.
Save AlexJuarez/c338afb427c2cf5efb8f058c2c4a8229 to your computer and use it in GitHub Desktop.
/**
* @param {string} color
* @return {string}
*/
const doubles = new Array(16).fill(0).map((_, i) => i * 17);
var similarRGB = function(color) {
const red = binarySearch(doubles, toRGB(color));
const blue = binarySearch(doubles, toRGB(color, 2));
const green = binarySearch(doubles, toRGB(color, 4));
return `#${toHex(red)}${toHex(blue)}${toHex(green)}`;
};
function toHex(val) {
if (val === 0) {
return '00';
}
return val.toString(16);
}
function binarySearch(arr, val, start = 0, end = arr.length - 1) {
while (start <= end) {
const mid = Math.floor((start + end) / 2);
if (arr[mid] > val) {
end = mid - 1;
} else if (arr[mid] < val) {
start = mid + 1;
} else {
return arr[mid];
}
}
return Math.abs(val - arr[end]) < Math.abs(val - arr[start]) ? arr[end] : arr[start];
}
function toRGB(hex, offset = 0) {
return parseInt(hex.substr(offset + 1, 2), 16);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment