Search code examples
javascriptpi

Get n number of points from angle 0 to 2π using an array operator like map or reduce?


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);

Solution

  • 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.