Created
January 24, 2019 00:00
-
-
Save hemanthpai/08098ff1c7477e37624dfcaf93d40f5e to your computer and use it in GitHub Desktop.
Color Utils Solution
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
//TODO: Implement hexToRgb | |
export const hexToRgb = (rgb:string) => { | |
const rgbComponents = extractComponents(rgb); | |
return {r: parseInt(rgbComponents.r, 16), | |
g: parseInt(rgbComponents.g, 16), | |
b: parseInt(rgbComponents.b, 16) | |
}; | |
} | |
const extractComponents = (rgb:string) => { | |
const red = rgb.slice(0, rgb.length/3); | |
const green = rgb.slice(rgb.length/3, 2*rgb.length/3); | |
const blue = rgb.slice(2*rgb.length/3, 3*rgb.length/3); | |
return {r: red.padStart(2, red), | |
g: green.padStart(2, green), | |
b: blue.padStart(2, blue) | |
} | |
} | |
//TODO: Implement rgbToHex | |
export const rgbToHex = (r:number, g:number, b:number) => { | |
const rString = padWithZero(roundToBounds(r).toString(16)); | |
const bString = padWithZero(roundToBounds(b).toString(16)); | |
const gString = padWithZero(roundToBounds(g).toString(16)); | |
return rString + gString + bString; | |
} | |
const roundToBounds = (num:number) : number => { | |
if(num > 255) { | |
return 255; | |
} else if(num < 0) { | |
return 0; | |
} else { | |
return num; | |
} | |
} | |
const padWithZero = (hex:string) : string => { | |
if(hex.length === 1) { | |
return hex.padStart(2, '0'); | |
} else { | |
return hex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment