Is it possible to unpack/destructure class attributes into variables?

65 views Asked by At

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

There are 2 answers

2
Konrad On

I couldn't find this option in the documentation, but you can overwrite this behaviour using Symbol.iterator

p5.Vector.prototype[Symbol.iterator] = function*() {
  yield this.x
  yield this.y
  yield this.z
}

function setup() {
  const v = createVector(1, 2, 3)
  console.log('test', ...v)
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>

0
Benilson On

One way to do this is to use Object.values to take the values from the vector object as an array and use the spread syntax when executing the function.

const createVector = (x, y) => {
  return {x: x, y: y};
}

const circle = (x, y, z) => {
  console.log(('x=' + x));
  console.log(('y=' + y));
  console.log(('z=' + z));
};

circle(...Object.values(createVector(1, 2)), 3);