Home > database >  Combine two color functions SASS
Combine two color functions SASS

Time:12-18

I have two SASS functions that do the same thing, with some differences. The first function iterates over the map, and then returns a short record so that you can conveniently use the work with color and transparency

// map
$colors: (
    primary: #06285c,
    seconadary: #96ccff,
    tertiary: #357edd,
    accent: #ff6300,
    info: #a463f2,
    success: #19a974,
    warning: #ffde37,
    danger: hsl(8deg 100% 61%)
);

@function color($key: primary, $opacity: 1) {
    @return rgba(map-get($colors, $key), $opacity); 
}

// sass style
background-color: color(warning, 0.6);

// compile to
background-color: rgba(255,0,0,.6);

My second function is designed to use whatever color is entered without having to rely on map

@function color-custom($key: primary, $opacity: 1) {
    $color: color($key);
    @return rgba($color, $opacity);
}

// sass style
background-color: color-custom(#ff0000, 0.6);

// compile to
background-color: rgba(255,0,0,.6);

I would just like to combine both functions into one. I do not know if this is possible, and how to check the dependencies inside the function. At the same time, these functions cannot exist, they give errors. Therefore, I would like to simply unite them, if it is possible.

CodePudding user response:

You can check if $key exists in your map with map-has-key and then set a condition to return the correct result:

@function get-color($key: primary, $opacity: 1) {
    $color: if(map-has-key($colors, $key), map-get($colors, $key), $key);
    @return rgba($color, $opacity);
}
  • Related