From e9263befeee65260af91f17432deb2d0e820f6ea Mon Sep 17 00:00:00 2001 From: Stefan Fejes Date: Mon, 26 Oct 2020 21:00:53 +0100 Subject: [PATCH] add lighten snippet --- snippets/lighten.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 snippets/lighten.md diff --git a/snippets/lighten.md b/snippets/lighten.md new file mode 100644 index 000000000..327a5a891 --- /dev/null +++ b/snippets/lighten.md @@ -0,0 +1,28 @@ +--- +title: lighten +tags: string,browser,regexp,beginner +--- + +Returns the string value for the lightened color in `hsl` format. + +- Use `String.prototype.match()` to get an array of 3 string with the numeric values. +- Use `Array.prototype.map()` in combination with `Number` to convert them into an array of numeric values. +- Clamp new lightness within the hsl valid range between `0` and `100`. +- Form a valid `hsl` color string. + +```js +const lighten = (amount, hslStr) => { + const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number); + + const newLightness = Math.max( + 0, + Math.min(100, lightness + parseFloat(amount)) + ); + + return `hsl(${hue}, ${saturation}%, ${newLightness}%)`; +}; +``` + +```js +lighten(10, "hsl(330, 50%, 50%)"); // 'hsl(330, 50%, 60%)' +```