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

Ensure alpha is a number in Color constructor #400

Merged
merged 5 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class Color {
this.coords = coords ? coords.slice() : [0, 0, 0];

// Clamp alpha to [0, 1]
this.alpha = alpha > 1 ? 1 : (alpha < 0 ? 0 : alpha);
this.alpha = alpha > 1 || alpha === undefined ? 1 : (alpha < 0 ? 0 : alpha);

// Convert "NaN" to NaN
for (let i = 0; i < this.coords.length; i++) {
Expand Down
30 changes: 29 additions & 1 deletion test/construct.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Color from "../src/index.js";
import { check } from "./util.mjs";
import { isNone } from "../src/util.js";

export default {
name: "Constructor tests",
Expand All @@ -8,7 +9,14 @@ export default {
let color = new Color(...args);
return color.toJSON();
},
check: check.deep(),
check: check.deep(function (actual, expect) {
if (expect === null || isNone(expect)) {
// Treat NaN and null as equivalent for now
return actual === null || isNone(actual);
}

return check.equals(actual, expect);
}),
tests: [
{
name: "Basic constructors",
Expand Down Expand Up @@ -36,11 +44,31 @@ export default {
args: ["hsl(10, 50%, 50%)"],
expect: { "spaceId": "hsl", "coords": [ 10, 50, 50 ], "alpha": 1 }
},
{
name: "new Color(hsl string), none alpha",
args: ["hsl(10, 50%, 50% / none)"],
expect: { "spaceId": "hsl", "coords": [ 10, 50, 50 ], "alpha": NaN }
},
{
name: "new Color({spaceId, coords})",
args: [{spaceId: "p3", coords: [0, 1, 0]}],
expect: { "spaceId": "p3", "coords": [ 0, 1, 0 ], "alpha": 1 }
},
{
name: "new Color({spaceId, coords, alpha})",
args: [{spaceId: "p3", coords: [0, 1, 0], alpha: 0.5}],
expect: { "spaceId": "p3", "coords": [ 0, 1, 0 ], "alpha": 0.5 }
},
{
name: "new Color({spaceId, coords, alpha}), clamp alpha",
args: [{spaceId: "p3", coords: [0, 1, 0], alpha: 1000}],
expect: { "spaceId": "p3", "coords": [ 0, 1, 0 ], "alpha": 1 }
},
{
name: "new Color({spaceId, coords, alpha}), NaN alpha",
args: [{spaceId: "p3", coords: [0, 1, 0], alpha: NaN}],
expect: { "spaceId": "p3", "coords": [ 0, 1, 0 ], "alpha": NaN }
},
]
}
]
Expand Down