From 3bda688b1e7122e39b71c3a05f7926136560c15a Mon Sep 17 00:00:00 2001 From: ztimson Date: Thu, 26 Dec 2024 10:40:39 -0500 Subject: [PATCH] added blackOrWhite color contrast function --- package.json | 2 +- src/color.ts | 12 ++++++++++++ src/index.ts | 1 + 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 src/color.ts diff --git a/package.json b/package.json index ccfbf79..0ce1fcd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.23.5", + "version": "0.23.6", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/color.ts b/src/color.ts new file mode 100644 index 0000000..9011690 --- /dev/null +++ b/src/color.ts @@ -0,0 +1,12 @@ +/** + * Determine if either black or white provides more contrast to the provided color + * @param {string} background Color to compare against + * @return {"white" | "black"} Color with the most contrast + */ +export function blackOrWhite(background: string): 'white' | 'black' { + const exploded = background.match(background.length >= 6 ? /\w\w/g : /\w/g); + if(!exploded) return 'black'; + const [r, g, b] = exploded.map(hex => parseInt(hex, 16)); + const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; + return luminance > 0.5 ? 'black' : 'white'; +} diff --git a/src/index.ts b/src/index.ts index 00fc828..1711665 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,7 @@ export * from './arg-parser'; export * from './array'; export * from './aset'; export * from './cache'; +export * from './color'; export * from './csv'; export * from './files'; export * from './emitter';