All files / util parseRGB.js

100% Statements 15/15
100% Branches 6/6
100% Functions 3/3
100% Lines 15/15

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 38 39 40 41 42                            1x     9x 9x 1x   8x 1x     7x   7x 4x 12x     3x   7x 7x 21x       1x  
/**
 * rgb字符串解析
 * - 换算公式改编自 http://en.wikipedia.org/wiki/HSL_color_space.
 * - h, s, 和 l 设定在 [0, 1] 之间
 * - 返回的 r, g, 和 b 在 [0, 255]之间
 * @method util/parseRGB
 * @param {String} color 16进制色值
 * @returns {Array} RGB色值数值
 * @example
 * var $parseRGB = require('@spore-ui/kit/packages/util/parseRGB');
 * $parseRGB('#ffffff'); // => [255,255,255]
 * $parseRGB('#fff'); // => [255,255,255]
 */
 
const REG_HEX = /(^#?[0-9A-F]{6}$)|(^#?[0-9A-F]{3}$)/i;
 
function parseRGB(color) {
  var 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('#', '');
  var arr;
  if (str.length === 3) {
    arr = str.split('').map(function (c) {
      return c + c;
    });
  } else {
    arr = str.match(/[a-fA-F0-9]{2}/g);
  }
  arr.length = 3;
  return arr.map(function (c) {
    return parseInt(c, 16);
  });
}
 
module.exports = parseRGB;