optimized color parsing

This commit is contained in:
Daniel Sommer 2022-02-25 15:39:32 +01:00
parent 750844f49e
commit 421c3be3dd

View file

@ -1,7 +1,6 @@
const logger = require('./logger.js');
const hexcolor = require('hex-color-regex'); const hexcolor = require('hex-color-regex');
const LEDS_ALL = require('./blinkstick.js').LEDS_ALL; const LEDS_ALL = require('./blinkstick.js').ALL;
const MODE_SET = require('./blinkstick.js').MODE_SET; const MODE_SET = require('./blinkstick.js').MODE_SET;
const MODE_MORPH = require('./blinkstick.js').MODE_MORPH; const MODE_MORPH = require('./blinkstick.js').MODE_MORPH;
const MODE_BLINK = require('./blinkstick.js').MODE_BLINK; const MODE_BLINK = require('./blinkstick.js').MODE_BLINK;
@ -115,20 +114,18 @@ function parseColor(value) {
if (value === undefined || value === COLOR_RANDOM) { if (value === undefined || value === COLOR_RANDOM) {
return COLOR_RANDOM; return COLOR_RANDOM;
} }
let parsedColor = parseRGBColor(value); let parsedColor = parseHexColor(value);
if (!parsedColor) { if (parsedColor !== undefined) {
parsedColor = parseHexColor(value); return parsedColor;
} }
return parsedColor || function () { return parseRGBColor(value) || COLOR_RANDOM;
logger.warn('could not parse color value \'' + value + '\', defaulting to \'' + COLOR_RANDOM + '\'');
return COLOR_RANDOM;
}();
} }
function parseRGBColor(value) { function parseRGBColor(value) {
if (value.indexOf(',') === -1 && isRGBValue(value)) { if (value.indexOf(',') === -1 && isRGBValue(value)) {
return convertRGBToHex(parseInt(value) || 0, 0, 0); value = parseInt(value);
} else { return convertRGBToHex(value, value, value);
}
const splittedValues = value.split(','); const splittedValues = value.split(',');
let color = {}; let color = {};
for (let index = 0; index < splittedValues.length; index++) { for (let index = 0; index < splittedValues.length; index++) {
@ -144,7 +141,6 @@ function parseRGBColor(value) {
if (isRGBValue(color.red) && isRGBValue(color.green) && isRGBValue(color.blue)) { if (isRGBValue(color.red) && isRGBValue(color.green) && isRGBValue(color.blue)) {
return convertRGBToHex(color.red, color.green, color.blue); return convertRGBToHex(color.red, color.green, color.blue);
} }
}
} }
function isRGBValue(value) { function isRGBValue(value) {
@ -159,12 +155,13 @@ function parseHexColor(value) {
if (value[0] !== '#') { if (value[0] !== '#') {
value = '#' + value; value = '#' + value;
} }
if (value.length === 4) { if (value.length !== 7) {
value = (value[0] + value[1] + value[1] + value[2] + value[2] + value[3] + value[3]); return;
}
if (!hexcolor({strict: true}).test(value)) {
return;
} }
if (hexcolor({strict: true}).test(value)) {
return value; return value;
}
} }
// exports // exports