chaos/scripts/chaos.js

49 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 `point`, generate `iterations` points
* by applying randomly-chosen transformations
*
* @param {Array} point 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
* @return {Array} Generated points
*/
export const applyChaos = (point, iterations, transforms, weights) => {
const points = [];
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);
}
return points;
};