chaos/scripts/chaos.js

48 lines
1.2 KiB
JavaScript

'use strict';
/**
* Choose an index at random among a list of weights,
* more weighted indices have a greater proability to be chosen
*
* @param {Array} weights List of weights
* @return {number} Selected index
*/
const chooseIndex = weights => {
const number = Math.random();
let sum = 0, index = 0;
while (number >= sum) {
sum += weights[index];
index += 1;
}
return index - 1;
};
/**
* Starting from the last point in `points`, add
* `iterations` number of point generated by applying
* transformations chosen at random among `transforms`
*
* @param {Array} points Initial set of points
* @param {number} iterations Number of points to plot
* @param {Array} transforms List of available transforms
* @param {Array} weights Probability weights for each transform
* @return {null}
*/
export const applyChaos = (points, iterations, transforms, weights) => {
let point = points[points.length - 1];
if (weights === undefined) {
weights = Array.apply(null, Array(transforms.length)).map(
() => 1 / transforms.length
);
}
while (iterations--) {
const index = chooseIndex(weights);
point = transforms[index](point);
points.push(point);
}
};