Imagine needing the points to draw a sine wave:
let points = [];
for(var angle = 0; angle < Math.PI * 2; angle += .01) {
points.push(Math.sin(angle));
}
console.log(points);
Now imagine that we want to control the amount of points but still getting a full rotation of 2π:
const pointsArr = new Array(10000).fill().map((i) => {
// how to convert above loop
});
console.log(pointsArr);
You could generate the array using Array.from
:
function makePoints(numPoints) {
const diffBetweenPoints = (Math.PI * 2) / (numPoints - 1);
return Array.from({ length: numPoints }, (_, i) => Math.sin(i * diffBetweenPoints));
}
console.log(makePoints(5));
The second argument provided to Array.from
is an optional map
function that behaves identically to Array.prototype.map
.