Last active
March 21, 2019 01:36
-
-
Save nabn/50d909d16a1fd241b87e90cba01f6c8d to your computer and use it in GitHub Desktop.
Convert between hex and rgb colour values using Ramda
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
import { __, compose, concat, join, | |
map, match, propEq, replace, | |
splitEvery, unnest, when } from "ramda"; | |
/* | |
* USAGE | |
* let hex = '#fff54a' | |
* let rgb = 'rgb(255,245,74)' | |
* rgbToHex(rgb) // #fff54a | |
* hexToRgb(hex) // rgb(255,245,74) | |
*/ | |
const toHex = x => x.toString(16); | |
const fromHex = x => parseInt(x, 16); | |
const strToNum = x => parseInt(x, 10); | |
const duplicate = unnest(concat) | |
const normalize = when(propEq("length", 1), duplicate); | |
const strToHex = compose(normalize, toHex, strToNum); | |
const wrapRgb = compose( | |
concat(__, ")"), | |
concat("rgb(") | |
); | |
export const rgbToHex = compose( | |
concat("#"), | |
join(""), | |
map(strToHex), | |
match(/(\d{1,3})/g) | |
); | |
export const hexToRgb = compose( | |
wrapRgb, | |
join(","), | |
map(fromHex), | |
splitEvery(2), | |
replace(/^#/, "") | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link to Ramda REPL with this code