Created
May 4, 2019 21:00
-
-
Save nikoheikkila/01b02b627ede66999ba789d154a32f49 to your computer and use it in GitHub Desktop.
TypeScript: RGB Class Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Difference = (a: number, b: number) => number | |
export default class Color { | |
protected red: number | |
protected green: number | |
protected blue: number | |
protected opacity?: number | |
static HEX_MIN = 0 | |
static HEX_MAX = 255 | |
constructor(red: number, green: number, blue: number, opacity?: number) { | |
this.red = red | |
this.green = green | |
this.blue = blue | |
this.opacity = opacity || 1.0 | |
} | |
public toString(): string{ | |
return `rgba(${this.red}, ${this.green}, ${this.blue}, ${this.opacity})` | |
} | |
public toHex(): string { | |
return '#' + [ | |
this.red, | |
this.green, | |
this.blue | |
] | |
.map((c: number): string => `0${c.toString(16)}`.slice(-2).toUpperCase()) | |
.join('') | |
} | |
public invert(): Color { | |
return new Color( | |
Color.HEX_MAX - this.red, | |
Color.HEX_MAX - this.green, | |
Color.HEX_MAX - this.blue | |
) | |
} | |
public difference(c: Color, diff?: Difference): Color { | |
if (!diff) { | |
diff = (a, b) => Math.abs(a - b) | |
} | |
return new Color( | |
diff(this.red, c.red), | |
diff(this.green, c.green), | |
diff(this.blue, c.blue) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment