Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. (function(window){
  2.     "use strict";
  3.     var parseInt = window.parseInt
  4.  
  5.     function solidColor(r,g,b) {
  6.         if (!this) return new solidColor(r,g,b);
  7.         this.type = "solid";
  8.         this.red = r;
  9.         this.green = g;
  10.         this.blue = b;
  11.         Object.freeze(this);
  12.     }
  13.     function alphaColor(r,g,b,a) {
  14.         if (!this) return new alphaColor(r,g,b,a);
  15.         this.type = "alpha";
  16.         this.red = r;
  17.         this.green = g;
  18.         this.blue = b;
  19.         this.alpha = a;
  20.         Object.freeze(this);
  21.     }
  22.     function unknownColor() {
  23.         if (!this) return new unknownColor();
  24.         this.type = "unknown";
  25.         Object.freeze(this);
  26.     }
  27.  
  28.     function parseHexColor(rawstr) {
  29.         rawstr = rawstr.trim().substring(1);
  30.         if (rawstr.length === 8) {
  31.             return alphaColor(
  32.                 parseInt(rawstr.substring(0,2), 16), parseInt(rawstr.substring(2,4), 16),
  33.                 parseInt(rawstr.substring(4,6), 16), parseInt(rawstr.substring(4,6), 16)
  34.             );
  35.         } else if (rawstr.length === 4) {
  36.             return alphaColor(
  37.                 parseInt(rawstr[0], 16) * 0x11, parseInt(rawstr[1], 16) * 0x11, parseInt(rawstr[2], 16) * 0x11, parseInt(rawstr[3], 16) * 0x11
  38.             );
  39.         } else if (rawstr.length === 6) {
  40.             return solidColor(
  41.                 parseInt(rawstr.substring(0,2), 16), parseInt(rawstr.substring(2,4), 16), parseInt(rawstr.substring(4,6), 16)
  42.             );
  43.         } else if (rawstr.length === 3) {
  44.             return alphaColor( parseInt(rawstr[0], 16) * 0x11, parseInt(rawstr[1], 16) * 0x11, parseInt(rawstr[2], 16) * 0x11 );
  45.         }
  46.         return unknownColor();
  47.     }
  48.  
  49.     // the red component of green
  50.     console.log(parseHexColor("#0f0").red);
  51.     // the alpha of transparent purple
  52.     console.log(parseHexColor("#f0f7").alpha);
  53.     // the entire color for turquoise
  54.     console.log(parseHexColor("#40E0D0"));
  55. })(self);