Skip to content

Commit

Permalink
feat: support getter when no prop
Browse files Browse the repository at this point in the history
  • Loading branch information
wzc520pyfm committed Apr 6, 2024
1 parent e0e84af commit 99c2034
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { mycolor } from "ohcolor";
import mycolor from "ohcolor";

mycolor("#ff3399").rgba(); // [255, 51, 153, 1]
mycolor("#ff3399").red(); // 255
mycolor(255, 165, 0, 1).red(133).rgba(); // [133, 165, 0, 1]
mycolor(255, 165, 0, 1).green(34).rgba(); // [255, 34, 0, 1]
mycolor(255, 165, 0, 1).blue(99).rgba(); // [255, 165, 99, 1]
Expand Down
32 changes: 28 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,13 @@ abstract class Color<CS extends ColorSpace> {
interface RGB<CS extends Extract<ColorSpace, "rgb"> = "rgb"> {
/** @description Get rgba array by standard methods */
rgba(): TColorRGB;
red(): RGB_R;
red(r: RGB_R): Color<CS>;
green(): RGB_G;
green(g: RGB_G): Color<CS>;
blue(): RGB_B;
blue(b: RGB_B): Color<CS>;
alpha(): Alpha;
alpha(a: Alpha): Color<CS>;
}

Expand Down Expand Up @@ -170,19 +174,39 @@ class RGBColor<CS extends Extract<ColorSpace, "rgb"> = "rgb">
return [this.r, this.g, this.b, this.a];
}

red(r: number): RGBColor<CS> {
red(): RGB_R;
red(r: RGB_R): RGBColor<CS>;
red(r?: RGB_R): RGB_R | RGBColor<CS> {
if (U.u(r)) {
return this.r;
}
return Utils.w(r, this.g, this.b, this.a);
}

green(g: number): RGBColor<CS> {
green(): RGB_G;
green(g: RGB_G): RGBColor<CS>;
green(g?: RGB_G): RGB_G | RGBColor<CS> {
if (U.u(g)) {
return this.g;
}
return Utils.w(this.r, g, this.b, this.a);
}

blue(b: number): RGBColor<CS> {
blue(): RGB_B;
blue(b: RGB_B): RGBColor<CS>;
blue(b?: RGB_B): RGB_B | RGBColor<CS> {
if (U.u(b)) {
return this.b;
}
return Utils.w(this.r, this.g, b, this.a);
}

alpha(a: number): RGBColor<CS> {
alpha(): Alpha;
alpha(a: Alpha): RGBColor<CS>;
alpha(a?: Alpha): Alpha | RGBColor<CS> {
if (U.u(a)) {
return this.a;
}
return Utils.w(this.r, this.g, this.b, a);
}
}
Expand Down
5 changes: 5 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ describe("mycolor", () => {
const color2 = color1.alpha(0.1);
expect(color1).not.toEqual(color2);

expect(mycolor(255, 165, 0, 1).red()).toEqual(255);
expect(mycolor(255, 165, 0, 1).green()).toEqual(165);
expect(mycolor(255, 165, 0, 1).blue()).toEqual(0);
expect(mycolor(255, 165, 0, 1).alpha()).toEqual(1);

expect(mycolor(255, 165, 0, 1).red(133).rgba()).toEqual([133, 165, 0, 1]);
expect(mycolor(255, 165, 0, 1).green(34).rgba()).toEqual([255, 34, 0, 1]);
expect(mycolor(255, 165, 0, 1).blue(99).rgba()).toEqual([255, 165, 99, 1]);
Expand Down

0 comments on commit 99c2034

Please sign in to comment.