0

I have a javascript array defined as below:

var hexgon = ['M',r*Math.cos(0/180*Math.PI),r*Math.sin(0/180*Math.PI)                               
                                    ,r*Math.cos(30/180*Math.PI),r*Math.sin(30/180*Math.PI)
                                    ,r*Math.cos(90/180*Math.PI),r*Math.sin(90/180*Math.PI)
                                    ,r*Math.cos(150/180*Math.PI),r*Math.sin(150/180*Math.PI)
                                    ,r*Math.cos(210/180*Math.PI),r*Math.sin(210/180*Math.PI)
                                    ,r*Math.cos(270/180*Math.PI),r*Math.sin(270/180*Math.PI),
                                    ,r*Math.cos(330/180*Math.PI),r*Math.sin(330/180*Math.PI),'Z']

How to use a loop to simplify this logic?

3
  • can u find a pattern with 0,30,90,150,210,270,330 Commented Oct 31, 2022 at 19:13
  • Maybe we can change it to -30,30,90,150,210,270, so +60 each cycle! Commented Oct 31, 2022 at 19:16
  • something like this even works without being too complex ['M',...[-30,30,90,150,210,270].flatMap((x) => [r*Math.cos(x/180*Math.PI),r*Math.sin(x/180*Math.PI)]),'Z'] Commented Oct 31, 2022 at 19:28

2 Answers 2

1

If you did not intend two commas in a row after the twelth element then this:

var hexgon = ['M', ...[0,30,90,150,210,270,330].flatMap(d => [r*Math.cos(d/180*Math.PI),r*Math.sin(d/180*Math.PI)]), 'Z']
Sign up to request clarification or add additional context in comments.

Comments

1

If you can have a constant value as a step that gets added to Math.cos() and Math.sin() statements we might be able to do something.

Let's say we want to add 30 each time to the each array's element, we can do something like this: (Also noticed there are M and Z characters at the beginning and end of your array)

const newHexgon = new Array(16);
newHexgon[0] = 'M';
newHexgon[newHexgon.length - 1] = 'Z';
let counter = 0;
let step = 30;
for (let i = 1; i < newHexgon.length - 1; i += 2) {
  newHexgon[i] = Math.cos(((counter * step) / 180) * Math.PI);
  newHexgon[i + 1] = Math.sin(((counter * step) / 180) * Math.PI);
  counter++;
}

console.log(newHexgon);

I created an array with a length of 16 and set the first and last elements to "M" and "Z" as in your array. Then I will loop every two elements at a time i += 2 and set the Math calculations and after finished in each iteration the counter gets added by one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.