From f955fbe7987b919850cbb10f85fc95532bc7111b Mon Sep 17 00:00:00 2001 From: Matt Walker Date: Mon, 16 Dec 2013 21:58:16 -0800 Subject: [PATCH] Added out-of-bounds handling for hslToRgb function with unit tests --- lib/colors/hsl-to-hex.js | 16 +++++++++++++++- test/unit-test.js | 30 +++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/lib/colors/hsl-to-hex.js b/lib/colors/hsl-to-hex.js index 09a676a4b..6bb503128 100644 --- a/lib/colors/hsl-to-hex.js +++ b/lib/colors/hsl-to-hex.js @@ -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); diff --git a/test/unit-test.js b/test/unit-test.js index d872288e1..74ba6d0a5 100644 --- a/test/unit-test.js +++ b/test/unit-test.js @@ -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({