Create a colour matching ts code
- User
Create a colour matching ts code
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Create a colour matching ts code
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
If by "colour matching ts code" you mean TypeScript code that can be used to match or compare colors, the following example should be helpful. This TypeScript code defines a simple color matching utility that can compare two colors based on their hexadecimal values to see if they are the same or similar within a certain tolerance.
type RGBColor = {
r: number;
g: number;
b: number;
};
class ColorMatcher {
private static hexToRgb(hex: string): RGBColor | null {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
static areColorsMatching(hex1: string, hex2: string, tolerance: number = 0): boolean {
const rgb1 = this.hexToRgb(hex1);
const rgb2 = this.hexToRgb(hex2);
if (!rgb1 || !rgb2) {
throw new Error('Invalid HEX color.');
}
return (
Math.abs(rgb1.r - rgb2.r) <= tolerance &&
Math.abs(rgb1.g - rgb2.g) <= tolerance &&
Math.abs(rgb1.b - rgb2.b) <= tolerance
);
}
}
// Example usage:
const color1 = '#ff00ff';
const color2 = '#fc00fc';
const tolerance = 3; // You can adjust the tolerance level
try {
const isMatch = ColorMatcher.areColorsMatching(color1, color2, tolerance);
console.log(`The colors ${color1} and ${color2} are ${isMatch ? '' : 'not '}matching within the tolerance of ${tolerance}.`);
} catch (error) {
console.error(error);
}
This code provides a ColorMatcher class with a static method areColorsMatching, which takes two hexadecimal color values as input and checks if they are similar within a given tolerance. It also includes a helper function hexToRgb to convert hexadecimal color values to RGB.
You can adjust the tolerance to define how close the colors need to be to be considered a match. A tolerance of 0 means the colors have to be exactly the same, whereas higher values allow for some variation between the colors.
Please note that this example uses a simple RGB comparison, which may not account for perceptual color differences. For more advanced color matching, you might want to look into color difference algorithms like CIE76, CIE94, CIEDE2000, or use libraries that implement these algorithms.