Code coverage report for hex2rgb/index.js

Statements: 100% (22 / 22)      Branches: 100% (20 / 20)      Functions: 100% (1 / 1)      Lines: 100% (22 / 22)      Ignored: none     

All files » hex2rgb/ » index.js
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                  1       18 1     17   17 17 17 17   17             17 1       17   17 7 7 7   7 7   10 1     17               1
/**
 * hex2rgb
 * https://github.com/glnster/hex2rgb
 *
 * Copyright (c) 2015 Glenn Cueto
 * Licensed under the MIT license.
 *
 * Converts hex color to rgb. Calculates corresponding foreground.
 *
 * @param {string} hex - The hex color to be converted. Can be 3 or 6 HEX-ONLY chars.
 * @param {boolean} debug - Optional. Default=false.
 * @param {string} darkyiq, lightyiq - Optional foreground colors.
 * @return {array} rgb - [x,x,x] or default [0,0,0].
 * @return {string} yiq - Default 'black' or 'white' as a foreground color
 *                        against the given hex.
 */
 
var hex2rgb = function(hex, options) {
  'use strict';
 
  // checks and defaults
  if (typeof hex !== 'string') {
    throw new TypeError('Expected a string');
  }
 
  hex = hex.replace(/^#/, '');
 
  options = options || {};
  options.debug = (typeof options.debug === 'boolean') ? options.debug : false;
  options.rgbStringDefault = (typeof options.rgbStringDefault === 'string') ? options.rgbStringDefault : 'inherit';
  options.yiqDefault = (typeof options.yiqDefault === 'string') ? options.yiqDefault : 'inherit';
 
  var hlen = hex.length,
    cleanHex,
    RGB = [255, 255, 255],
    rgbString = options.rgbStringDefault,
    yiqres = options.yiqDefault;
 
  // expand hex input
  if (hlen === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
 
  // check for hex-only chars
  cleanHex = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
 
  if (cleanHex !== null) {
    var num = parseInt(cleanHex, 16);
    RGB = [num >> 16, num >> 8 & 255, num & 255];
    rgbString = 'rgb(' + RGB[0] + ', ' + RGB[1] + ', ' + RGB[2] + ')';
 
    var yiq = ((RGB[0] * 299) + (RGB[1] * 587) + (RGB[2] * 114)) / 1000;
    yiqres = (yiq >= 128 || isNaN(yiq)) ? 'black' : 'white';
 
  } else if (options.debug === true) {
    console.error('(hex2rgb) ' + hex + ': Expected 3 or 6 HEX-ONLY chars. Returning defaults.');
  }
 
  return {
    rgb: RGB,
    rgbString: rgbString,
    yiq: yiqres
  };
 
};
 
module.exports = hex2rgb;