Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// hex is the node value
const hex = node.value;
// conditionally expand a hex
const hex8 = `0x${hex.length === 5 ? hex.slice(1).replace(/[0-9A-f]/g, '$&$&') : hex.slice(1)}`;
// extract the red, blue, green, and alpha values from the hex
const [r, g, b, a] = [
parseInt(hex8.slice(2, 4), 16),
parseInt(hex8.slice(4, 6), 16),
parseInt(hex8.slice(6, 8), 16),
Math.round(parseInt(hex8.slice(8, 10), 16) / 255 * alphaDecimalPrecision) / alphaDecimalPrecision
];
// return a new rgba function, preserving the whitespace of the original node
const rgbaFunc = valueParser.func({ value: 'rgba', raws: Object.assign({}, node.raws) });
rgbaFunc.append(valueParser.paren({ value: '(' }));
rgbaFunc.append(valueParser.number({ value: r }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: g }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: b }));
rgbaFunc.append(valueParser.comma({ value: ',' }));
rgbaFunc.append(valueParser.number({ value: a }));
rgbaFunc.append(valueParser.paren({ value: ')' }));
return rgbaFunc;
};