chaos/scripts/chaos.js

49 lines
1.2 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
};
/**
2015-12-23 21:31:51 +00:00
* Starting from `point`, generate `iterations` points
* by applying randomly-chosen transformations
2015-12-22 20:33:40 +00:00
*
2015-12-23 21:31:51 +00:00
* @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
2015-12-23 21:31:51 +00:00
* @return {Array} Generated points
2015-12-22 20:33:40 +00:00
*/
2015-12-23 21:31:51 +00:00
export const applyChaos = (point, iterations, transforms, weights) => {
const points = [];
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);
points.push(point);
2015-12-22 20:33:40 +00:00
}
2015-12-23 21:31:51 +00:00
return points;
2015-12-22 20:33:40 +00:00
};