From 0b355756c66ddc5a86beb1073f624b003ad5edef Mon Sep 17 00:00:00 2001 From: christian-bromann Date: Thu, 5 Jul 2018 18:52:07 +0200 Subject: [PATCH] better handle alpha values --- index.js | 2 +- rgb2hex.js | 2 +- rgb2hex.min.js | 2 +- test/rgb2hex.test.js | 4 +++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index a1a1ac4..202e7c2 100644 --- a/index.js +++ b/index.js @@ -28,7 +28,7 @@ var rgb2hex = module.exports = function rgb2hex(color) { /** * parse input */ - var digits = /(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,[01]??\.([0-9]{0,3}))??\)/.exec(strippedColor); + var digits = /(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,(1|0??\.([0-9]{0,3})))??\)/.exec(strippedColor); if(!digits) { // or throw error if input isn't a valid rgb(a) color diff --git a/rgb2hex.js b/rgb2hex.js index e4383b7..a6ccd48 100644 --- a/rgb2hex.js +++ b/rgb2hex.js @@ -21,7 +21,7 @@ /** * parse input */ - var digits = /(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,[01]??\.([0-9]{0,3}))??\)/.exec(strippedColor); + var digits = /(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,(1|0??\.([0-9]{0,3})))??\)/.exec(strippedColor); if(!digits) { // or throw error if input isn't a valid rgb(a) color diff --git a/rgb2hex.min.js b/rgb2hex.min.js index 2cf1ec3..26f018c 100644 --- a/rgb2hex.min.js +++ b/rgb2hex.min.js @@ -1 +1 @@ -!function(r){var e=function(r){if("string"!=typeof r)throw new Error("color has to be type of `string`");if("#"===r.substr(0,1))return{hex:r,alpha:1};var e=r.replace(/\s+/g,""),t=/(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,[01]??\.([0-9]{0,3}))??\)/.exec(e);if(!t)throw new Error("given color ("+r+") isn't a valid rgb or rgba color");var n=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),i=t[6]?/([0-9\.]+)/.exec(t[6])[0]:"1",s=(a|o<<8|n<<16|1<<24).toString(16).slice(1);return"."===i.substr(0,1)&&(i=parseFloat("0"+i)),1 { }) it('by limiting alpha value to 1', () => { - var input = 'rgba(12,173,22,1.67)' + var input = 'rgba(236,68,44,1)' expect(rgb2hex(input).alpha).not.toBeGreaterThan(1) }) @@ -95,6 +95,8 @@ describe('rgb2hex should', () => { expect(() => rgb2hex(input)).toThrow(invalidErrorMessage(input)) input = 'rgbaaaaaa(113, 54, 4, .33)' expect(() => rgb2hex(input)).toThrow(invalidErrorMessage(input)) + input = 'rgba(12,173,22,1.67)' + expect(() => rgb2hex(input)).toThrow(invalidErrorMessage(input)) }) })