AniUI Academy
hard+350 XPPractice

Compute a WCAG contrast ratio

"Is this grey readable on white?" has an exact answer, defined by WCAG, and it is a short piece of arithmetic. Implementing it is how the rule that body text needs 4.5:1 stops being folklore.

Implement contrastRatio(hexA, hexB). Each argument is a hex colour, with or without a leading #, in either the 6-digit or 3-digit shorthand form, case-insensitive.

For each colour, convert every channel to c = value / 255, then linearise it: if c is less than or equal to 0.03928 use c / 12.92, otherwise use Math.pow((c + 0.055) / 1.055, 2.4). The relative luminance is 0.2126 * R + 0.7152 * G + 0.0722 * B of those linearised channels.

The ratio is (lighter + 0.05) / (darker + 0.05) where lighter is the larger of the two luminances, so the result is always at least 1 and does not depend on argument order. Return the raw unrounded number — the tests round it themselves with Math.round(value * 100) / 100.

What it has to do

  • Accept 6-digit and 3-digit hex colours, with or without #, in any case.
  • Linearise each channel with the 0.03928 threshold, / 12.92 below it and the 2.4 power above it.
  • Weight the channels 0.2126, 0.7152 and 0.0722 for relative luminance.
  • Return (lighter + 0.05) / (darker + 0.05), so the result never depends on argument order.
  • Return the raw number without rounding it yourself.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.