olov/defs

Any plan to add supports for destructuring and default parameters?

termi opened this issue · 3 comments

I think it's not hard to support such basic ES6 features as destructuring and default parameters, due coffescript has it already. But I personally don't like default variable implementation in coffescript, due this:

function foo(a) {
    if(a == null) a = 'blah'
}

I think operator === would be more accurate. But arguments.length would be even more accurate.

Example:

function foo(a, bar = 123) {
    [a, bar] = [bar, a];

    setTimeout(function timeout() {
        console.log(a, bar);
        // cleanup
        a = bar = null;
    })
}
foo(321)

output:

function foo(a, bar) {
    if( arguments.length < 2 ) {
        bar = 123;
    }

    var a$0 = a;
    a = bar;
    bar = a;
    a$0 = null;//this is important

    setTimeout(function timeout() {
        console.log(a, bar)
        // cleanup
        a = bar = null;
    })
}
foo(321)

As you can see I insist on cleaning a$0 variable due scope in timeout function has link to a$0.

More examples of destructuring

function foo() {
  return [1, 2];
}

var [a, b] = foo();

output:

function foo() {
  return [1, 2];
}

var foo$0 = foo()
     , a = foo$0[0]
     , b = foo$0[1]
;
foo$0 = null;//this is important

Ignoring some returned values

function foo() {
  return [1, 2, 3];
}

var [a, , b] = foo();
console.log("A is " + a + " B is " + b);

output:

function foo() {
  return [1, 2, 3];
}

var foo$0 = foo()
     , a = foo$0[0]
     , b = foo$0[2]
;
foo$0 = null;//this is important

You can ignore any (or all) returned values this way. For example:

function foo() {
  return [1, 2, 3];
}

var [,,] = foo();

output:

function foo() {
  return [1, 2, 3];
}

foo();

Destructuring assignment in the context of Object:

var o = { name: 'Alex', permissions: 'Admin', email: 'alex@example.com' };
var {name, email} = o;
console.log(name + email)

output:

var o = { 'name': 'Alex', permissions: 'Admin', email: 'alex@example.com' };
var name = o['name'], email = o.email;
console.log(name + email)

In this example bracket notation is very important

olov commented

There are lots of interesting features coming in ES6 but the scope [sic!] for defs.js is bringing ES6 block scope, with const and let, to ES3. For other features, including destructuring, I recommend checking out Traceur.

I am using Traceur right now and quality of the output code makes me sad.
P.S. I don't really understand the right translation for word defs

olov commented

defs is short for defines or definitions, whichever pleases you the most. :)