* Gets the nearest color, from the given list of ColorSpec objects * (which defaults to nearestColor.DEFAULT_COLORS). * * Probably you wouldn't call this method directly. Instead you'd get a custom * color matcher by calling nearestColor.from. * * @public * @param {RGB
(needle: RGB | string, colors: Array<ColorSpec>)
| 31 | * nearestColor('foo'); // => throws |
| 32 | */ |
| 33 | function nearestColor(needle: RGB | string, colors: Array<ColorSpec>): string { |
| 34 | needle = parseColor(needle); |
| 35 | |
| 36 | let distanceSq; |
| 37 | let minDistanceSq = Infinity; |
| 38 | // eslint-disable-next-line one-var |
| 39 | let rgb; |
| 40 | // eslint-disable-next-line one-var |
| 41 | let value: ColorSpec; |
| 42 | |
| 43 | for (let i = 0; i < colors.length; ++i) { |
| 44 | rgb = colors[i].rgb; |
| 45 | |
| 46 | distanceSq = |
| 47 | (needle.r - rgb.r) ** 2 + |
| 48 | (needle.g - rgb.g) ** 2 + |
| 49 | (needle.b - rgb.b) ** 2; |
| 50 | |
| 51 | if (distanceSq < minDistanceSq) { |
| 52 | minDistanceSq = distanceSq; |
| 53 | value = colors[i]; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | // @ts-expect-error this is always not null |
| 58 | return value.source; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Given either an array or object of colors, returns an array of |
no test coverage detected