Speeds up HexNameShortener.
authorJakub Pawlowicz <contact@jakubpawlowicz.com>
Sat, 4 Oct 2014 23:30:45 +0000 (00:30 +0100)
committerJakub Pawlowicz <contact@jakubpawlowicz.com>
Fri, 10 Oct 2014 20:22:45 +0000 (21:22 +0100)
* Moves regex creation out of loop.
* Makes #shorten a simple function.

lib/colors/hex-name-shortener.js
lib/selectors/optimizers/simple.js
test/colors/hex-name-shortener-test.js

index 914b235..ce4acc6 100644 (file)
@@ -1,6 +1,4 @@
-function HexNameShortener(value) {
-  this.value = value;
-}
+var HexNameShortener = {};
 
 var COLORS = {
   aliceblue: '#f0f8ff',
@@ -164,18 +162,17 @@ for (var name in COLORS) {
     toHex[name] = hex;
 }
 
-HexNameShortener.prototype.shorten = function () {
-  var data = this.value;
-
-  [toHex, toName].forEach(function(conversion) {
-    var pattern = '(' + Object.keys(conversion).join('|') + ')';
-    var colorSwitcher = function(match, colorValue, suffix) {
-      return conversion[colorValue.toLowerCase()] + suffix;
-    };
-    data = data.replace(new RegExp(pattern + '( |,|\\)|$)', 'ig'), colorSwitcher);
-  });
+var toHexPattern = new RegExp('(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig');
+var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')( |,|\\)|$)', 'ig');
 
-  return data;
+HexNameShortener.shorten = function (value) {
+  return value
+    .replace(toHexPattern, function(match, colorValue, suffix) {
+      return toHex[colorValue.toLowerCase()] + suffix;
+    })
+    .replace(toNamePattern, function(match, colorValue, suffix) {
+      return toName[colorValue.toLowerCase()] + suffix;
+    });
 };
 
 module.exports = HexNameShortener;
index 6b7e59f..2ce8211 100644 (file)
@@ -120,6 +120,9 @@ function multipleZerosMinifier(property, value) {
 }
 
 function colorMininifier(property, value, compatibility) {
+  if (value.indexOf('#') === -1 && value.indexOf('rgb') == -1 && value.indexOf('hsl') == -1)
+    return HexNameShortener.shorten(value);
+
   value = value
     .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function (match, red, green, blue) {
       return new RGB(red, green, blue).toHex();
@@ -155,7 +158,7 @@ function colorMininifier(property, value, compatibility) {
     });
   }
 
-  return new HexNameShortener(value).shorten();
+  return HexNameShortener.shorten(value);
 }
 
 function reduce(body, options) {
index 4060bd3..e5cab0b 100644 (file)
@@ -158,7 +158,7 @@ function colorShorteningContext() {
 
   function shortened(target) {
     return function (source) {
-      assert.equal(new HexNameShortener(source).shorten(), target);
+      assert.equal(HexNameShortener.shorten(source), target);
     };
   }