UNPKG

@onesy/utils

Version:
22 lines (19 loc) 1.24 kB
import is from './is'; import isValid from './isValid'; import clamp from './clamp'; import castParam from './castParam'; const hexToRgb = function (value) { let opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; let array = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (isValid('color-hex', value)) { const hex = value.slice(1); let r = parseInt(hex.length === 3 ? "".concat(hex[0]).concat(hex[0]) : hex.slice(0, 2), 16); let g = parseInt(hex.length === 3 ? "".concat(hex[1]).concat(hex[1]) : hex.slice(2, 4), 16); let b = parseInt(hex.length === 3 ? "".concat(hex[2]).concat(hex[2]) : hex.slice(4, 6), 16); let a = opacity !== undefined ? opacity > 1 ? (opacity / 100).toFixed(2) : clamp(opacity, 0, 1) : hex.length === 8 && (parseInt(hex.slice(6), 16) / 255).toFixed(2); const values = [...[r, g, b].map(item => Math.round(castParam(item))), is('number', a) && +a]; [r, g, b, a] = values; return array ? values.filter(value_ => is('number', value_)) : "rgb".concat(is('number', a) ? 'a' : '', "(").concat(r, ", ").concat(g, ", ").concat(b).concat(is('number', a) ? ", ".concat(a) : '', ")"); } }; export default hexToRgb;