All files / util parseRGB.ts

85.71% Statements 12/14
100% Branches 0/0
100% Functions 3/3
83.33% Lines 10/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37                          1x   1x 7x               7x 7x   6x   5x   7x 21x     1x  
/**
 * rgb字符串解析
 * - 返回的 r, g, 和 b 在 [0, 255]之间
 * @see http://en.wikipedia.org/wiki/HSL_color_space
 * @method parseRGB
 * @param {String} color 16进制色值
 * @returns {Array} RGB色值数值
 * @example
 * import { parseRGB } from '@spore-ui/tskit';
 * parseRGB('#ffffff'); // => [255,255,255]
 * parseRGB('#fff'); // => [255,255,255]
 */
 
const REG_HEX = /(^#?[0-9A-F]{6}$)|(^#?[0-9A-F]{3}$)/i;
 
export function parseRGB(color: string): number[] {
  let str = color;
  if (typeof str !== 'string') {
    throw new Error('Color should be string');
  }
  if (!REG_HEX.test(str)) {
    throw new Error('Wrong RGB color format');
  }
 
  str = str.replace('#', '');
  let arr = [];
  if (str.length === 3) {
    arr = str.split('').map((c: string) => (c + c));
  } else {
    arr = str.match(/[a-fA-F0-9]{2}/g);
  }
  arr.length = 3;
  return arr.map((c) => parseInt(c, 16));
}
 
export default parseRGB;