Skip to content

Instantly share code, notes, and snippets.

@nabn
Last active March 21, 2019 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nabn/50d909d16a1fd241b87e90cba01f6c8d to your computer and use it in GitHub Desktop.
Save nabn/50d909d16a1fd241b87e90cba01f6c8d to your computer and use it in GitHub Desktop.
Convert between hex and rgb colour values using Ramda
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(/^#/, "")
);
@nabn
Copy link
Author

nabn commented Mar 20, 2019

Link to Ramda REPL with this code

@nabn
Copy link
Author

nabn commented Mar 20, 2019

There are more efficient ways to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment