* Parses a color from a string. * * @private * @param {RGB|string} source * @return {RGB} * * @example * parseColor({ r: 3, g: 22, b: 111 }); // => { r: 3, g: 22, b: 111 } * parseColor('#f00'); // => { r: 255, g: 0, b: 0 } * parseColor('#04fbc8'); // => { r: 4
(source: RGB | string)
| 149 | * parseColor('foo'); // => throws |
| 150 | */ |
| 151 | function parseColor(source: RGB | string): RGB { |
| 152 | let red, green, blue; |
| 153 | |
| 154 | if (typeof source === "object") { |
| 155 | return source; |
| 156 | } |
| 157 | |
| 158 | let hexMatchArr = source.match(/^#?((?:[0-9a-f]{3}){1,2})$/i); |
| 159 | if (hexMatchArr) { |
| 160 | const hexMatch = hexMatchArr[1]; |
| 161 | |
| 162 | if (hexMatch.length === 3) { |
| 163 | hexMatchArr = [ |
| 164 | hexMatch.charAt(0) + hexMatch.charAt(0), |
| 165 | hexMatch.charAt(1) + hexMatch.charAt(1), |
| 166 | hexMatch.charAt(2) + hexMatch.charAt(2), |
| 167 | ]; |
| 168 | } else { |
| 169 | hexMatchArr = [ |
| 170 | hexMatch.substring(0, 2), |
| 171 | hexMatch.substring(2, 4), |
| 172 | hexMatch.substring(4, 6), |
| 173 | ]; |
| 174 | } |
| 175 | |
| 176 | red = parseInt(hexMatchArr[0], 16); |
| 177 | green = parseInt(hexMatchArr[1], 16); |
| 178 | blue = parseInt(hexMatchArr[2], 16); |
| 179 | |
| 180 | return { r: red, g: green, b: blue }; |
| 181 | } |
| 182 | |
| 183 | throw Error(`"${source}" is not a valid color`); |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Creates a {@link ColorSpec} from either a string or an {@link RGB}. |
no outgoing calls
no test coverage detected