function hex2rgba(hex) {
function isFormatted(hex) {
if (hex[0] != '#') {
return Array.from(hex).every(char => !isNaN(parseInt(char, 16)))
} else {
return Array.from(hex.slice(1)).every(char => !isNaN(parseInt(char, 16)))
}
}
function hex2num (h) {
return parseInt(h, 16) / (h.length > 1 ? 255 : 15)
}
if (!isFormatted (hex)) {
throw TypeError(`${hex} is not a hex color`)
}
if (hex.length == 3) {
return {
r: hex2num(hex.slice(0 ,1)),
g: hex2num(hex.slice(1, 2)),
b: hex2num(hex.slice(2, 3)),
a: 1
}
} else if (hex.length == 4) {
if (hex[0] == '#') {
return {
r: hex2num(hex.slice(1, 2)),
g: hex2num(hex.slice(2, 3)),
b: hex2num(hex.slice(3, 4)),
a: 1
}
} else {
return {
r: hex2num(hex.slice(0 ,1)),
g: hex2num(hex.slice(1, 2)),
b: hex2num(hex.slice(2, 3)),
a: hex2num(hex.slice(3, 4))
}
}
} else if (hex.length == 5) {
return {
r: hex2num(hex.slice(1, 2)),
g: hex2num(hex.slice(2, 3)),
b: hex2num(hex.slice(3, 4)),
a: hex2num(hex.slice(4, 5))
}
} else if (hex.length == 6) {
return {
r: hex2num(hex.slice(0, 2)),
g: hex2num(hex.slice(2, 4)),
b: hex2num(hex.slice(4, 6)),
a: 1
}
} else if (hex.length == 7) {
return {
r: hex2num(hex.slice(1, 3)),
g: hex2num(hex.slice(3, 5)),
b: hex2num(hex.slice(5, 7)),
a: 1
}
} else if (hex.length == 8) {
return {
r: hex2num(hex.slice(0, 2)),
g: hex2num(hex.slice(2, 4)),
b: hex2num(hex.slice(4, 6)),
a: hex2num(hex.slice(6, 8))
}
} else if (hex.length == 9) {
return {
r: hex2num(hex.slice(1, 3)),
g: hex2num(hex.slice(3, 5)),
b: hex2num(hex.slice(5, 7)),
a: hex2num(hex.slice(7, 9))
}
} else {
throw TypeError(`${hex} is not a hex color`)
}
}