chaos/scripts/chaos.js

50 lines
1.3 KiB
JavaScript
Raw Normal View History

2015-12-22 20:33:40 +00:00
'use strict';
/**
* Choose an index at random among a list of weights,
* more weighted indices have a greater proability to be chosen
2015-12-22 20:33:40 +00:00
*
* @param {Array} weights List of weights
* @return {number} Selected index
2015-12-22 20:33:40 +00:00
*/
const chooseIndex = weights => {
const number = Math.random();
let sum = 0, index = 0;
2015-12-22 20:33:40 +00:00
while (number >= sum) {
sum += weights[index];
index += 1;
2015-12-22 20:33:40 +00:00
}
return index - 1;
2015-12-22 20:33:40 +00:00
};
/**
* Apply the chaos game: starting from `start`, we plot
* the next `n` points. To get to the next point, we apply
* a random transformation among given ones
2015-12-22 20:33:40 +00:00
*
* @param {ImageData} image Image to write on
* @param {Array} start Starting point
* @param {number} iterations Number of points to plot
* @param {Array} transforms List of available transforms
* @param {Array} weights Probability weights for each transform
2015-12-22 20:33:40 +00:00
* @return {null}
*/
export const applyChaos = (image, start, iterations, transforms, weights, cb) => {
let point = start;
2015-12-22 20:33:40 +00:00
if (weights === undefined) {
weights = Array.apply(null, Array(transforms.length)).map(
() => 1 / transforms.length
);
}
2015-12-22 20:33:40 +00:00
while (iterations--) {
const index = chooseIndex(weights);
point = transforms[index](point);
2015-12-22 20:33:40 +00:00
cb(point);
2015-12-22 20:33:40 +00:00
}
};