Skip to content

Instantly share code, notes, and snippets.

@aneudy1702
Last active August 1, 2019 18:31
Show Gist options
  • Save aneudy1702/36f119469064550e6de81ed4ae374b08 to your computer and use it in GitHub Desktop.
Save aneudy1702/36f119469064550e6de81ed4ae374b08 to your computer and use it in GitHub Desktop.
A function that takes 2 colors as arguments and returns the average color.
/**
*
Write a function that takes 2 colors as arguments and returns the average color.
- The parameters will be two 6-digit hexadecimal strings. This does not need to be validated.
- The return value should be a 6-digit hexadecimal string.
- The hexadecimal strings represent colors in RGB, much like in CSS.
- The average color is to be determined by taking the arithmetic mean for each component: red, green and blue.
**/
/**
* @author: aneudy abreu(@aneudy1702)
**/
const averageColorStr = (colorA, colorB) => {
// get RGB colors
const [redA, greenA, blueA] = getColorRGBArray(colorA)
const [redB, greenB, blueB] = getColorRGBArray(colorB)
// get mean(average) colors
const meanRed = getMean(redA, redB)
const meanGreen = getMean(greenA, greenB)
const meanBlue = getMean(blueA, blueB)
// get and return hex string
return getColorHexString(meanRed, meanGreen, meanBlue)
/**
* UTILITY METHODS BELLOW
* */
/**
* This methods will transform any hex color into an array
* of corresponding RGB values.
* @param color = 6 digit hex color. eg.: ffffff
* @return Array<Numbers> array of numbers from 0 to 255
* */
function getColorRGBArray(color) {
const pairs = color.toString().match(/.{1,2}/g) || []
return pairs.map(cHex => (
parseInt(cHex, 16)
))
}
/**
* This method expects N amount parameters that get
* turn into hex values and returned as a string.
* @param colorDigits <Array<Integers>> is rested array of parameters
* containing integers. eg.: getColorHexString(255, 255, 255)
* @return string containing a hex string. eg.: 'ffffff'
* */
function getColorHexString(...colorDigits) {
return (
colorDigits.map(c => `${c < 10 ? '0': ''}${c.toString(16)}`).join('')
)
}
/**
* This methods calculates the mean average of list of numbers.
* @param numbers<Array<Integers>> is rested array of parameters
* expected to be integers.
* @return an integer representing the average of the passed numbers.
* */
function getMean(...numbers) {
return Math.round(
numbers.reduce(
(a, b) => a + b,
0
) /
numbers.length
)
}
}
// this randomColor logic is courtesey of Paul Iris https://www.paulirish.com/2009/random-hex-color-code-snippets/
const randomColor = () => Math.floor(Math.random()*16777215).toString(16)
const colorA = randomColor()
const colorB = randomColor()
// { colorA: '882d6d', colorB: '64a5a9', average: '76698b' }
console.log({
colorA,
colorB,
average: averageColorStr(colorA, colorB)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment