tc39 / proposal-extractors

Extractors for ECMAScript
http://tc39.es/proposal-extractors/
MIT License
200 stars 3 forks source link

Add example for if / while let bindings #5

Closed MaxGraey closed 5 months ago

MaxGraey commented 1 year ago

Firstly, thanks for the great proposal! In addition to more proper usage for Pattern Matching, it would be nice to add usage examples for "if let" binding as well. It related to another abandoned proposal: https://github.com/tc39/proposal-Declarations-in-Conditionals which may become new life with combining with extractors.

if (let Binary{ lhs, rhs } = expr) { // will not throw exception when failure!
   // use lhs, rhs if `expr instanceof Binary` 
}

Which more or less equivalent to:

if (expr instanceof Binary) {
   let { lhs, rhs } = expr;
   // use lhs, rhs
}
bakkot commented 1 year ago

+1 to this idea.

In proposal-Declarations-in-Conditionals you enter the if if the RHS is truthy. That's not really the same thing as this proposal, where you enter the if if the RHS matches the pattern on the LHS.

Also, consider destructuring. Would if (let [a] = null) { ... } else { ... } throw, the way let [a] = null does, or would it enter the else, like for a failed extraction?

Anyway I'm not totally sure it would make sense to have the if (let x = y) form in addition to the if (let Some[x] = y) form. Maybe? But certainly it could be done as a follow-on, if we wanted.

If we do have to pick between then, if (let Some[x] = y) as proposed in this issue is definitely more useful.


Note that this issue title is a little confusing; you're asking for a feature to be added to the proposal, not for an example of an existing feature to put into the readme (which is what I assumed). Maybe rename this issue to "add if/while let bindings"?

rbuckton commented 5 months ago

This is something that is covered by the Pattern Matching proposal as something like:

if (expr is Binary({ let lhs, let rhs })) {
  // use lhs, rhs
}