- Notifications
You must be signed in to change notification settings - Fork4
CS2 Discussion: Output: Destructuring #69
Description
Building off of#18, we should consider changing CoffeeScript’s destructuring output from the current ES3 to ESNext syntax. So this:
numbers= [1,2,3]pairs= {a:1,b:2,c:3 }[one,two,three]= numbers{one,two,three}= pairsfoo=-> [@a,@b,@c]= numbers {@a,@b,@c}= pairsreturn
which currently compiles to this:
varfoo,numbers,one,pairs,three,two;numbers=[1,2,3];pairs={a:1,b:2,c:3};one=numbers[0],two=numbers[1],three=numbers[2];one=pairs.one,two=pairs.two,three=pairs.three;foo=function(){this.a=numbers[0],this.b=numbers[1],this.c=numbers[2];this.a=pairs.a,this.b=pairs.b,this.c=pairs.c;};
would instead compile tothis (?):
varfoo,numbers,one,pairs,three,two;numbers=[1,2,3];pairs={a:1,b:2,c:3};[one,two,three]=numbers;({one, two, three}=pairs);foo=function(){[this.a,this.b,this.c]=numbers;({a:this.a,b:this.b,c:this.c}=pairs);};
The array destructuring, as you can see here, is pretty straightforward; but the object destructuring presents issues. First, if we’re not declaring the variable at the same time (as we never do in CoffeeScript, hence thevar
line of declarations at the top of each scope) then we need to wrap the destructuring assignment in parentheses,per MDN. And if the target variable is attached tothis
, we need to use the“assigning to new variable names” shortcut to destructure into our intended destination variable, unless people have a better suggestion for how to handle this.
There’s also the question of whether this is worth the effort. The current output is already rather readable, so the gains aren’t great. Destructuring, whether in CS or ES, is just a time-saver; anything you can do with destructuring you can also already do in more verbose variable assignment, so there’s no compatibility need for us to change anything. If anything, the lack of need behooves us to make sure that if we make this change, it is done in a fully backward compatible way.
Edit: Fixed destructuring object withthis
per@lydell’s correction.