Destructuring assignment during the cycle in the ES6 function does not extend from the cycle?

I implemented a simple GCD algorithm in ES6 (via node-esml) and came across (me) strange behavior with updating variable values โ€‹โ€‹inside a while loop. This code works fantastically:

function gcdWithTemp(x, y) { let [r, rdash] = [x, y] while (r != 0) { q = Math.floor(rdash / r) temp = r r = rdash - q * r rdash = temp } return(rdash) } console.log(gcdWithTemp(97, 34)) 

Returning the expected response 1 . However, if I delete the temporary variable and use the destructuring assignment instead to try to achieve the same results:

 function gcdWithDestructuredAssignment(x, y) { let [r, rdash] = [x, y] while (r != 0) { q = Math.floor(rdash / r) [r, rdash] = [rdash - q * r, r] } return(rdash) } console.log(gcdWithDestructuredAssignment(97, 34)) 

This never completes, further debugging shows that r will always have the first value assigned, x . It seems that these two implementations should be the same? see Exchange of variables

I also tried using var instead of let no avail. Do I really do not understand the point of restructuring the task or is something missing? Or is this a mistake?

+5
source share
1 answer

This is not a problem with the purpose of destructuring, but with ASI (automatic semicolon). These two lines:

 q = Math.floor(rdash / r) [r, rdash] = [rdash - q * r, r] 

in practice, it means:

 q = Math.floor(rdash / r)[r, rdash] = [rdash - q * r, r] 

which is obviously not what you had in mind. To fix this, add a semicolon before [ :

 function gcdWithDestructuredAssignment(x, y) { let [r, rdash] = [x, y] while (r != 0) { q = Math.floor(rdash / r) ;[r, rdash] = [rdash - q * r, r] } return(rdash) } console.log(gcdWithDestructuredAssignment(97, 34)) 

Of course, you can add the missing semicolon at the end of the previous line ( q = Math.floor(rdash / r); ), but since you usually don't use semicolons, I assumed that you are using the npm coding style .

+7
source

Source: https://habr.com/ru/post/1257391/


All Articles