contrast color

by Soviut

JavaScript

function contrastColor(hex, light, dark) {
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  let rgb = result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : {
  	r: 0,
    g: 0,
    b: 0
  };

	return (rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114) > 186 ? dark : light;
}

console.log(contrastColor('#FF0', '#FFF', '#000'))