Added out-of-bounds handling for hslToRgb function with unit tests
authorMatt Walker <matt@suckerfish.net>
Tue, 17 Dec 2013 05:58:16 +0000 (21:58 -0800)
committerMatt Walker <matt@suckerfish.net>
Thu, 19 Dec 2013 00:37:52 +0000 (16:37 -0800)
lib/colors/hsl-to-hex.js
test/unit-test.js

index 09a676a..6bb5031 100644 (file)
@@ -4,8 +4,22 @@ module.exports = function HSLToHex(data) {
   var hslToRgb = function(h, s, l) {
     var r, g, b;
 
+    // normalize hue orientation b/w 0 and 360 degrees
+    h = h % 360;
+    if (h < 0)
+      h += 360;
     h = ~~h / 360;
+
+    if (s < 0)
+      s = 0;
+    else if (s > 100)
+      s = 100;
     s = ~~s / 100;
+
+    if (l < 0)
+      l = 0;
+    else if (l > 100)
+      l = 100;
     l = ~~l / 100;
 
     if (s === 0) {
@@ -34,7 +48,7 @@ module.exports = function HSLToHex(data) {
 
   return {
     process: function() {
-      return data.replace(/hsl\((\d+),(\d+)%?,(\d+)%?\)/g, function(match, hue, saturation, lightness) {
+      return data.replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function(match, hue, saturation, lightness) {
         var asRgb = hslToRgb(hue, saturation, lightness);
         var redAsHex = asRgb[0].toString(16);
         var greenAsHex = asRgb[1].toString(16);
index d872288..74ba6d0 100644 (file)
@@ -656,7 +656,35 @@ vows.describe('clean-units').addBatch({
       'a{color:hsl(360,100%,50%)}',
       'a{color:red}'
     ],
-    'hsla not to hex': 'a{color:hsl(99,66%,33%,.5)}'
+    'hsla not to hex': 'a{color:hsl(99,66%,33%,.5)}',
+    'hsl out of bounds #1': [
+      'a{color:hsl(120,200%,50%)}',
+      'a{color:#0f0}'
+    ],
+    'hsl out of bounds #2': [
+      'a{color:hsl(120,-100%,50%)}',
+      'a{color:#7f7f7f}'
+    ],
+    'hsl out of bounds #3': [
+      'a{color:hsl(480,100%,25%)}',
+      'a{color:#007f00}'
+    ],
+    'hsl out of bounds #4': [
+      'a{color:hsl(-240,100%,75%)}',
+      'a{color:#7fff7f}'
+    ],
+    'hsl out of bounds #5': [
+      'a{color:hsl(-600,100%,75%)}',
+      'a{color:#7fff7f}'
+    ],
+    'hsl out of bounds #6': [
+      'a{color:hsl(0,0%,122%)}',
+      'a{color:#fff}'
+    ],
+    'hsl out of bounds #7': [
+      'a{color:hsl(0,0%,-10%)}',
+      'a{color:#000}'
+    ]
   }),
   'shortening colors': colorShorteningContext(),
   'font weights': cssContext({