Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[getAll] Support precision, closes #542 #548

Merged
merged 10 commits into from
Jun 12, 2024
19 changes: 15 additions & 4 deletions src/getAll.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ColorSpace from "./ColorSpace.js";
import getColor from "./getColor.js";
import { toPrecision } from "./util.js";

/** @typedef {import("./types.js").ColorTypes} ColorTypes */
/** @typedef {import("./types.js").Coords} Coords */
Expand All @@ -8,16 +9,26 @@ import getColor from "./getColor.js";
* Get the coordinates of a color in any color space
* @param {ColorTypes} color
* @param {string | ColorSpace} space The color space to convert to. Defaults to the color's current space
* @param {number} [precision] The number of significant digits to round the coordinates to
* @returns {Coords} The color coordinates in the given color space
*/
export default function getAll (color, space) {
export default function getAll (color, space, precision) {
color = getColor(color);

if (typeof space === "number") {
precision = space;
space = color.space;
}

let coords;
if (!space || color.space.equals(space)) {
// No conversion needed
return color.coords.slice();
coords = color.coords.slice();
}
else {
space = ColorSpace.get(space);
coords = space.from(color);
}

space = ColorSpace.get(space);
return space.from(color);
return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
}
14 changes: 14 additions & 0 deletions test/coords.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ export default {
},
expect: [1, 0, 0],
},
{
name: "color.getAll(1)",
run () {
return this.data.red_oklch.getAll(1);
},
expect: [.6, .3, 30],
},
{
name: "color.getAll('oklch', 1)",
run () {
return this.data.red.getAll("oklch", 1);
},
expect: [.6, .3, 30],
},
{
name: "color.alpha",
run () {
Expand Down
Loading