Test color algorithms
// uses mocha | |
const { rgb } = require("wcag-contrast"); | |
const fromHex = require("@fantasy-color/from-hex").default; | |
const fs = require("fs"); | |
const assert = require("assert"); | |
const parsedColors = fs | |
.readFileSync(__dirname + "/../parsed-colors.txt") | |
.toString() | |
.split("\n") | |
.map(colors => colors.split(" ")); | |
function isDarkColor(color) { | |
const [r, g, b] = hexToRGBArray(color); | |
const yiq = (r * 299 + g * 587 + b * 114) / 1000; | |
// Note: the value 150 is hardcoded into GitHub | |
return yiq < 150; | |
} | |
const oldMethod = color => (isDarkColor(color) ? "#000000" : "#ffffff"); | |
function yc(color) { | |
const t = "string" == typeof color ? parseInt(color.replace("#", ""), 16) : color; | |
return +((299 * ((t >> 16) & 255) + 587 * ((t >> 8) & 255) + 114 * (255 & t)) / 1e3 / 255).toFixed(2) < 0.6 | |
? "#ffffff" | |
: "#000000"; | |
} | |
const hexToRGBArray = color => { | |
const { red, green, blue } = fromHex(color); | |
return [red, green, blue]; | |
}; | |
const calcFontColor = color => { | |
const blackContrastScore = rgb(hexToRGBArray(color), [0, 0, 0]); | |
const whiteContrastScore = rgb(hexToRGBArray(color), [255, 255, 255]); | |
return blackContrastScore >= whiteContrastScore ? "#000000" : "#ffffff"; | |
}; | |
it("wcag method", () => { | |
let misses = 0; | |
parsedColors.forEach(([color, expectedColor]) => { | |
if (calcFontColor(color) !== expectedColor) { | |
misses++; | |
} | |
}); | |
assert.equal(misses, 0); | |
}); | |
it("oldMethod", () => { | |
let misses = 0; | |
parsedColors.forEach(([color, expectedColor]) => { | |
if (oldMethod(color) !== expectedColor) { | |
misses++; | |
} | |
}); | |
assert.equal(misses, 0); | |
}); | |
it("yc", () => { | |
let misses = 0; | |
parsedColors.forEach(([color, expectedColor]) => { | |
if (yc(color) !== expectedColor) { | |
misses++; | |
} | |
}); | |
assert.equal(misses, 0); | |
}); |
mocha test/color-alg-test.js | |
1) wcag method | |
2) oldMethod | |
3) yc | |
0 passing (31ms) | |
3 failing | |
1) wcag method: | |
AssertionError [ERR_ASSERTION]: 29 == 0 | |
+ expected - actual | |
-29 | |
+0 | |
at Context.it (test/color-alg-test.js:47:10) | |
2) oldMethod: | |
AssertionError [ERR_ASSERTION]: 2903 == 0 | |
+ expected - actual | |
-2903 | |
+0 | |
at Context.it (test/color-alg-test.js:57:10) | |
3) yc: | |
AssertionError [ERR_ASSERTION]: 1049 == 0 | |
+ expected - actual | |
-1049 | |
+0 | |
at Context.it (test/color-alg-test.js:67:10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment