React change function to return from string to boolean value

Viewed 26

Iam getting stuck on changing my code to return boolean values. Currently it returning string values but because of the lint issues I have to import the colors from an ui or feat component where I can use this function.

This is an code to changing the text color if the background color is dark or light. If the hsp > 127.5 it should return a text color else another. How I could handle this and how to use in other component?

This is my code:

Getting error with these imports. Thats why I need to return boolean values to set the color in ui component

import { textEmphasis, textOnInteractive } from '@vetera-sky/shared/ui';

export const getTextColorBaseOnBackground = (color: string): string => {
  let r, g, b;
  let clonedColor;

  if (clonedColor?.match(/^rgb/)) {
    clonedColor = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
    r = clonedColor[1];
    g = clonedColor[2];
    b = clonedColor[3];
  } else {
    clonedColor = +('0x' + color?.slice(1).replace(color.length < 5 && /./g, '$&$&'));
    r = clonedColor >> 16;
    g = (clonedColor >> 8) & 255;
    b = clonedColor & 255;
  }
  const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));

  if (hsp > 127.5) {
    return textEmphasis;
  } else {
    return textOnInteractive;
  }
};
1 Answers

i'm not sure if i get ur question,

Maybe this help..

if (hsp > 127.5) {
    return {text: textEmphasis, rgb: {r, g, b}};
  } else {
    return {text: textOnInteractive, rgb: {r, g, b}};
  }

Then use it like this,

const {text, rgb: {r, g, b}} = getTextColorBaseOnBackground('rgba(0,0,0,1');
Related