Skip to content

Commit

Permalink
cache for stats
Browse files Browse the repository at this point in the history
  • Loading branch information
mcnuttandrew committed Sep 30, 2024
1 parent 6c3894e commit 6867fb5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
5 changes: 1 addition & 4 deletions apps/color-buddy/src/content-modules/LeftPanel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@
) {
// is contrast metric
if (!new Set(deltaMetrics).has(metric as any)) {
return colors.map((color) => {
const clr = color.toColorIO();
return clr.contrast(bg.toColorIO(), metric as any);
});
return colors.map((color) => color.contrast(bg, metric));
}
// is delta metric
const deltas = [];
Expand Down
31 changes: 30 additions & 1 deletion packages/palette/src/Color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type DistAlgorithm = "76" | "CMC" | "2000" | "ITP" | "Jz" | "OK";

const ColorIOCaches = new Map<string, ColorIO>();
const InGamutCache = new Map<string, boolean>();
const colorStateCache = new Map<string, number>();
/**
* The base class for all color spaces
*
Expand Down Expand Up @@ -143,10 +144,38 @@ export class Color {
if (!allowedAlgorithms.has(algorithm)) {
return 0;
}
const key = `${this.toString()}-${color.toString()}-${algorithm}`;

const left = this.toColorIO().to("srgb");
const right = color.toColorIO().to("srgb");
return left.deltaE(right, algorithm);
const val = left.deltaE(right, algorithm);
colorStateCache.set(key, val);
return val;
}
contrast(
color: Color,
algorithm:
| "76"
| "CMC"
| "2000"
| "ITP"
| "APCA"
| "WCAG21"
| "Michelson"
| "Weber"
| "Lstar"
| "DeltaPhi"
| "none"
): number {
const key = `${this.toString()}-${color.toString()}-${algorithm}`;
if (colorStateCache.has(key)) {
return colorStateCache.get(key)!;
}
const left = this.toColorIO().to("srgb");
const right = color.toColorIO().to("srgb");
const val = left.contrast(right, algorithm as any);
colorStateCache.set(key, val);
return val;
}
distance(color: Color, space: string): number {
const colorSpace = space || this.spaceName;
Expand Down

0 comments on commit 6867fb5

Please sign in to comment.