I have a .json file with name (string) and RGB (r, g, b: numbers) with 30.000 key-value pairs. I am looping the json multiple times per second to find the closest name to a given RGB color. Any idea how I can optimize the code or the json data to make it faster? Currently it works fine for the few calls per seconds, but after 30-50 calls per seconds there is noticeable lag.
[
{ "name": "Aare River", "rgb": { "r": 0, "g": 184, "b": 159 } },
{ "name": "Aare River Brienz", "rgb": { "r": 5, "g": 163, "b": 173 } },
{ "name": "Aarhusian Sky", "rgb": { "r": 17, "g": 80, "b": 175 } },
{ "name": "Abaddon Black", "rgb": { "r": 35, "g": 31, "b": 32 } },
]
fetch("/data/colorsNames.json")
.then((res) => res.json())
.then((data) => {
colorsNames = data;
});
function setColorName(color: string): void {
let closestColor = findClosestColorName(hexToRgb(color, false) as ColorRGB);
colorNameText.textContent = colorsNames[closestColor[0]].name;
}
function findClosestColorName(
color: ColorRGB
): [index: number, distance: number] {
let closestIndex = -1;
let closestDistance = Number.MAX_VALUE;
let distance = Number.MAX_VALUE;
for (let i = 0; i < colorsNames.length; i++) {
distance = getColorsDistance(color, colorsNames[i].rgb);
if (distance < closestDistance) {
closestIndex = i;
closestDistance = distance;
}
if (closestDistance === 0) return [closestIndex, closestDistance];
}
return [closestIndex, closestDistance];
function getColorsDistance(color: ColorRGB, match: ColorRGB): number {
return (
Math.abs(color.r - match.r) +
Math.abs(color.g - match.g) +
Math.abs(color.b - match.b)
);
}
}