Skip to content

Commit

Permalink
* added chroma.stdDeviation() to retrieve the variance in an array of…
Browse files Browse the repository at this point in the history
… colors as an RGBA component. See [Issue 328] (gka#328 (comment))

Signed-off-by: regorxxx <[email protected]>
  • Loading branch information
regorxxx committed Feb 20, 2024
1 parent 08f5eb6 commit f959202
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/utils/deviation.js
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;
};
28 changes: 28 additions & 0 deletions test/stddev.test.js
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);

0 comments on commit f959202

Please sign in to comment.