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