When given a hex-value, I aim to find the closest matching color name. For instance, if the hex-color is #f00
, the corresponding color name is red
.
'#ff0000' => 'red'
'#000000' => 'black'
'#ffff00' => 'yellow'
Currently, I employ the levenshtein-distance algorithm to determine the closest color name, which generally works well but not always as expected.
For instance:
'#0769ad' => 'chocolate'
'#00aaee' => 'mediumspringgreen'
Are there any suggestions to improve the accuracy of the result?
Below is the function I created to find the closest color:
Array.closest = (function () {
// http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
function levDist(s, t) {
if (!s.length) return t.length;
if (!t.length) return s.length;
return Math.min(
levDist(s.substring(1), t) + 1,
levDist(t.substring(1), s) + 1,
levDist(s.substring(1), t.substring(1)) + (s[0] !== t[0] ? 1 : 0)
);
}
return function (arr, str) {
// http://stackoverflow.com/q/11919065/1250044#comment16113902_11919065
return arr.sort(function (a, b) {
return levDist(a, str) - levDist(b, str);
});
};
}());
http://jsfiddle.net/ARTsinn/JUZVd/2/
Another concern is the performance. It appears there may be a significant issue causing slow processing (potentially related to the algorithm).