Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created May 4, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/01b02b627ede66999ba789d154a32f49 to your computer and use it in GitHub Desktop.
Save nikoheikkila/01b02b627ede66999ba789d154a32f49 to your computer and use it in GitHub Desktop.
TypeScript: RGB Class Example
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