colors study
by kassiomaia
JavaScript
const Colors = (function () {
function Color(value) {
Object.assign(this, { value })
}
Color.prototype = {
get r() {
return parseInt(this.value.slice(1, this.value.length).substr(0, 2), 16)
},
get g() {
return parseInt(this.value.slice(1, this.value.length).substr(3, 2), 16)
},
get b() {
return parseInt(this.value.slice(1, this.value.length).substr(4, 2), 16)
},
toRGB() {
return new RGB(this.r, this.g, this.b)
},
toHSL() {
return this.toRGB().toHSL()
}
}
function RGB(r, g, b) {
Object.assign(this, { r, g, b})
}
RGB.prototype = {
toMatrix() {
return [this.r, this.g, this.b]
},
get unitary() {
return this.toMatrix().map(value => value / 255)
},
get max() {
const [r, g, b] = this.unitary
return Math.max(r, g, b)
},
get min() {
const [r, g, b] = this.unitary
return Math.min(r, g, b)
},
get chroma() {
return (this.max - this.min)
},
get luminance() {
return Math.abs(this.max - this.min) / 2
},
get saturation() {
if (this.luminance <= 0.5) {
return (this.max - this.min) / (this.max + this.min)
}
return (this.max - this.min) / (2 - this.max + this.min)
},
get hue() {
const { max, min } = this
const [r, g, b] = this.unitary
const factor = (max - min)
let h = (function() {
if (r === max) {
return (g - b) / factor
} else if (g === max) {
return 2 + (b - r) / factor
} else if (b === max) {
return 4 + (r - g) / factor
}
}())
let angle = h * 180 / Math.PI
return (angle += angle < 0 ? 360 : 60, angle)
},
toString() {
const { r, g, b } = this
return `rgb(${r}, ${g}, ${b})`
},
toHSL() {
return new HSL(this.hue, this.saturation, this.luminance)
}
}
function HSL(h, s, l) {
Object.assign(this, { h, s, l })
}
...