2.8 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6a22d77ddf034bc4e35b1d5b | Challenge 354: Contrast Rating 3 | 28 | challenge-354 |
--description--
Given two arrays representing RGB values and a boolean indicating whether the text is large, return the WCAG contrast rating using the following method:
First, convert each RGB value to relative luminance:
- Divide each channel
[R, G, B]by 255 to get a value between0and1 - Apply the gamma correction formula to each channel:
- If the channel value is less than or equal to
0.04045:channel / 12.92 - Otherwise:
((channel + 0.055) / 1.055) ^ 2.4
- If the channel value is less than or equal to
- Calculate luminance:
0.2126 * R + 0.7152 * G + 0.0722 * B
Then, calculate the contrast ratio by adding 0.05 to each luminance value, then dividing the lighter one by the darker one. The lighter one will always be the first argument.
Return the rating based on the contrast ratio using the following table:
| Rating | Normal Text | Large Text |
|---|---|---|
"AAA" |
7.0+ | 4.5+ |
"AA" |
4.5+ | 3.0+ |
"Fail" |
below 4.5 | below 3.0 |
--hints--
getContrastRating([255, 255, 255], [0, 0, 0], false) should return "AAA".
assert.equal(getContrastRating([255, 255, 255], [0, 0, 0], false), "AAA");
getContrastRating([215, 188, 188], [55, 55, 55], false) should return "AA".
assert.equal(getContrastRating([215, 188, 188], [55, 55, 55], false), "AA");
getContrastRating([143, 144, 210], [46, 47, 61], false) should return "Fail".
assert.equal(getContrastRating([143, 144, 210], [46, 47, 61], false), "Fail");
getContrastRating([167, 167, 210], [53, 10, 53], true) should return "AAA".
assert.equal(getContrastRating([167, 167, 210], [53, 10, 53], true), "AAA");
getContrastRating([135, 147, 155], [60, 70, 90], true) should return "AA".
assert.equal(getContrastRating([135, 147, 155], [60, 70, 90], true), "AA");
getContrastRating([125, 210, 195], [105, 130, 90], true) should return "Fail".
assert.equal(getContrastRating([125, 210, 195], [105, 130, 90], true), "Fail");
--seed--
--seed-contents--
function getContrastRating(rgb1, rgb2, isLargeText) {
return rgb1;
}
--solutions--
function getContrastRating(rgb1, rgb2, isLargeText) {
function toLuminance([r, g, b]) {
return [r, g, b].map(channel => {
channel = channel / 255;
return channel <= 0.04045
? channel / 12.92
: ((channel + 0.055) / 1.055) ** 2.4;
}).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);
}
const l1 = toLuminance(rgb1);
const l2 = toLuminance(rgb2);
const ratio = (l1 + 0.05) / (l2 + 0.05);
if (isLargeText) {
if (ratio >= 4.5) return "AAA";
if (ratio >= 3.0) return "AA";
} else {
if (ratio >= 7.0) return "AAA";
if (ratio >= 4.5) return "AA";
}
return "Fail";
}