forked from gka/chroma.js
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* added chroma.stdDeviation() to retrieve the variance in an array of…
… colors as an RGBA component. See [Issue 328] (gka#328 (comment)) Signed-off-by: regorxxx <[email protected]>
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
const Color = require('../Color'); | ||
|
||
module.exports = (colors) => { | ||
colors = [...colors].map((color) => new Color(color).rgba()) | ||
const colorNum = colors.length; | ||
const results = Array.from(Array(colorNum), () => new Array(colorNum)); | ||
const mean = [0, 0, 0, 0]; | ||
for (let i = 0; i < colorNum; i++) { | ||
colors[i].forEach((c, j) => mean[j] += (j === 3 ? c * 255 : c)); | ||
} | ||
mean.forEach((c, i) => mean[i] /= colorNum); | ||
let stdDev = 0; | ||
for (let i = 0; i < colorNum; i++) { | ||
stdDev += colors[i].reduce((acc, curr, j) => acc + (curr - mean[j])**2, 0); | ||
} | ||
stdDev /= Math.max((colorNum - 1), 1) * 4; | ||
stdDev = Math.round(stdDev**(1/2)); | ||
return stdDev; | ||
}; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
const vows = require('vows') | ||
const assert = require('assert'); | ||
require('es6-shim'); | ||
|
||
const stdDeviation = require('../src/utils/deviation'); | ||
const Color = require('../src/Color');; | ||
|
||
const tests = { | ||
hex: {in: ['#D2691E', '#8B4513', '#A0522D','#0000FF', '#668B8B', '#FFC0CB'], out: 158}, | ||
rgba: {in: [[210,105,30,1],[139,69,19,1],[160,82,45,1],[0,0,255,1],[102,139,139,1],[255,192,203,1]], out: 158}, | ||
chromacolor: {in: ['#D2691E', '#8B4513', '#A0522D', '#0000FF', '#668B8B', '#FFC0CB'].map((color) => new Color(color)), out: 158}, | ||
}; | ||
|
||
const batch = {}; | ||
|
||
Object.keys(tests).forEach(key => { | ||
batch[`stdDeviation ${key}`] = { | ||
topic: tests[key], | ||
num(topic) { | ||
assert.deepStrictEqual(stdDeviation(topic.in), topic.out); | ||
}, | ||
} | ||
}) | ||
|
||
vows | ||
.describe('Testing standard deviation') | ||
.addBatch(batch) | ||
.export(module); |