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?
source share