'Destructuring within an argument list
Let's say I have the following function:
function get_scaled_coordinates(x, y, scale) {
return [x*scale, y*scale];
}
Is it possible if I have a single variable with [x,y] to pass to the function. Perhaps something similar to this, conceptually speaking:
let point = [1,1];
get_scaled_coordinates(**point, scale);
// instead of having to do get_scaled_coordinates(point[0], point[1], scale)
Solution 1:[1]
You could take an array as target for destructuring.
function get_scaled_coordinates([x, y], scale) {
return [x * scale, y * scale];
}
If you like to use higher dimensions, you could map the array with new values.
function get_scaled_coordinates(coordinates, scale) {
return coordinates.map(v => v * scale);
}
Solution 2:[2]
Perhaps something similar to this, conceptually speaking:
get_scaled_coordinates(**point, scale);
You seem to be looking for spread syntax in the function call:
get_scaled_coordinates(...point, scale);
No need to change the function, making it accept an array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
| Solution 2 | Bergi |
