I’m using P5.js, but the question is applicable to Javascript in general
In p5.js we have a class p5.Vector which is useful to manipulate vectors, since it already implements a variety of methods for vectors (addition, heading, magnitude, rotation…)
Vector components are stored in the x
and y
attributes, so they are intuitively easy to access
let myVector = createVector(1, 2);
myVector.x; // returns 1
Now, some functions in P5.js don’t accept vectors, but expect one parameter for x and one parameter for y
For example, drawing a circle:
circle(10, 20, 5); // draws a circle at position (10, 20) of diameter 5
Now the question:
My functions usually return vectors, and sometimes I want to use this vectors to call native P5.js functions that don’t accept vectors, but individual coordinates.
In this case, I use an auxiliary variable.
let myPosition = calculatePosition(); // calculatePosition returns a vector
circle(myPosition.x, myPosition.y, 5);
Is there a way that I could do that without using an auxiliary variable, and somehow unpack the x and y components so they get passed to the appropriate parameters of circle?
2
Answers
I couldn’t find this option in the documentation, but you can overwrite this behaviour using
Symbol.iterator
You can do this by creating an auxiliary method, which receives as a parameter the method that will be executed receiving x and y and the other parameters, the vector containing these values for x and y, and Rest parameters for the other parameters.