Created
March 28, 2019 06:50
-
-
Save sebassdc/f9f89b4f0317eac8675a05220da78149 to your computer and use it in GitHub Desktop.
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
// https://www.reddit.com/r/learnprogramming/comments/3456xv/convert_rgb_color_to_wavelengthfrequency/ | |
// https://www.alanzucconi.com/2015/09/30/colour-sorting/ | |
const WHITE_STRING = parseInt( 'FFFFFF', 16 ) | |
const NUMBER_OF_COLORS = 50 | |
const genRandomInt = (min, max) => Math.floor(Math.random() * (max - min)) + min | |
const getHueFromRGB = ({ red, green, blue }) => { | |
const min = Math.min(Math.min(red, green), blue); | |
const max = Math.max(Math.max(red, green), blue); | |
if (min === max) { | |
return 0; | |
} | |
let hue = 0 | |
if (max === red) { | |
hue = (green - blue) / (max - min); | |
} else if (max === green) { | |
hue = 2 + (blue - red) / (max - min); | |
} else { | |
hue = 4 + (red - green) / (max - min); | |
} | |
hue = hue * 60; | |
if (hue < 0) hue = hue + 360; | |
return Math.round(hue); | |
} | |
function hexToRgb(hex) { | |
var result = /([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); | |
return { | |
red: parseInt(result[1], 16), | |
green: parseInt(result[2], 16), | |
blue: parseInt(result[3], 16) | |
} | |
} | |
const getWavelengthFromHue = (hue) => { | |
return (891,42 - hue) / 1.37 | |
} | |
const waveLengthFromHEX = (hex) => { | |
const rgb = hexToRgb(hex) | |
const hue = getHueFromRGB(rgb) | |
const waveLength = getWavelengthFromHue(hue) | |
return waveLength | |
} | |
const printColor = color => { | |
console.log( `%c ${color}`, `background-color: #${color}` ) | |
} | |
let randomColors = [] | |
console.log ('===============RANDOM COLORS==================') | |
for (let i = 0; i <= NUMBER_OF_COLORS; i+=1) { | |
const number = genRandomInt(0, WHITE_STRING) | |
const color = (number).toString(16).padStart(6, '0').toUpperCase() | |
randomColors.push(color) | |
printColor(color) | |
} | |
randomColors.sort((a, b) => { | |
return waveLengthFromHEX(a) - waveLengthFromHEX(b) | |
}) | |
console.log ('') | |
console.log ('') | |
console.log ('') | |
console.log ('') | |
console.log ('===============SORTED COLORS==================') | |
randomColors.forEach(color => { | |
printColor(color) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment