Are you asking how to do the math, or do you understand the math and are asking about how to write it in JS?
if you don’t understand the math
(or try google)
if you do understand the math, try putting it into a function (e.g., make a pen) and then come back if you need help with a particular part. Make sure you also explain the math to us so we can help you effectively.