omgovich / colord

👑 A tiny yet powerful tool for high-performance color manipulations and conversions
https://colord.omgovich.ru
MIT License
1.67k stars 49 forks source link

Support approximative color to name #49

Closed GMartigny closed 3 years ago

GMartigny commented 3 years ago

When parsing to name using the plugin, if the color is not exactly the right value the result is undefined. At user level, it can be expected that the library always return a color name.

colord("#ff0000").toName(); // => red
colord("#fe0000").toName(); // => undefined

If failing to find a perfect match, the lib could search for the closest color. This behavior could also be activated by a parameter to the toName function.

omgovich commented 3 years ago

Hi! I would try to find a good way to implement that. The hardest part, I guess, is implementing a logic to find the closest Hex/RGB value.

GMartigny commented 3 years ago

This option imply looping through all existing colors, computing a distance to the requested value and keeping the lowest result. With 147 distincts colors, it shouldn't be to bad for performance.

omgovich commented 3 years ago

Thanks! Will try to implement that in a week. How do you think it better to call the new parameter?

colord("#fe0000").toName({ closest: true });  // "yellow"
colord("#fe0000").toName({ approximate: true });  // "yellow"
colord("#fe0000").toName({ strict: false });  // "yellow"
// ???
GMartigny commented 3 years ago

It depends on what you think the default behavior should be. I think that it should be changed with a true value. If the default behavior is having a proximity search, then you should go for strict or exact to disable it. Otherwise, if the default is NOT doing the search, then closest, nearest or approximate sounds better.

omgovich commented 3 years ago

Hi! Sorry for the super long delay (I had a wedding and a lot of other things last months). I finally found time to add the functionality:

// available in v2.5
colord("#fe0000").toName({ closest: true });  // "red"
GMartigny commented 3 years ago

Works perfectly, nice job !