tc39 / proposal-bind-operator

This-Binding Syntax for ECMAScript
1.75k stars 30 forks source link

Binding while destructuring #5

Closed domenic closed 8 years ago

domenic commented 9 years ago

I just ran into a case today where I wanted to convert an API from

function foo(doA, doB, doC) {
  doA();
  doB();
  doC();
}

to

function foo(myClass) {
  myClass.doA();
  myClass.doB();
  myClass.doC();
}

for performance and ergonomic benefits. (https://github.com/whatwg/streams/issues/309)

However, this has a pretty sad downside that I can't use destructuring for cases where it might be clearer. That is, this won't work:

function foo({ doA, doC }) {
  doA();
  doC();
}

It would be pretty cool if the method-extraction half of the bind operator could help me out in this context. Maybe...

function foo({ ::doA, ::doC }) {
  doA();
  doC();
}

or...

function foo(::{ doA, doC }) {
  doA();
  doC();
}
zenparsing commented 9 years ago

I can see how that would be useful. And natural if you view autobinding as a special "kind" of [[Get]].

I think the first option would be better. We'd have to special-case the object destructuring cover grammar to accept property names in the form

'::' IdentifierName

but only in destructuring patterns. It would have to be an error in an object literal, in the same way that

({ x = y });

is a syntax error.

Let's leave this open for now.

ckknight commented 9 years ago

In your proposed syntax, @domenic, how would one represent destructured parameters with mismatching key/identifiers?

Your example:

function foo({ ::doA, ::doC }) {
  doA();
  doC();
}

If we wanted to have a different identifier, which is more appropriate?

function foo({ doA: ::runA, doC: ::runC }) {
  runA();
  runC();
}

or

function foo({ ::doA: runA, ::doC: runC }) {
  runA();
  runC();
}

It seems like, at least with these syntaxes, there's an awful lot of overloading of what : means within destructuring.

domenic commented 9 years ago

I think it would be the former, { doA: ::runA, doC: ::runC }; the :: should be attached to the new variable.

zenparsing commented 8 years ago

Closing this for now, we can revisit later.

michaeljota commented 5 years ago

Can this proposal be reopen to focus on this? And maybe, another use cases similar to this one. This use case is not something that you could solve using the pipe operators, as what you want is actually have the function binded to the parameter.