proposal-refs icon indicating copy to clipboard operation
proposal-refs copied to clipboard

Possible use in custom extractors

Open dead-claudia opened this issue 7 years ago • 1 comments

I could see this being useful in defining custom destructuring extractors, like let #Some(x) = .... Hypothetically, it could be as simple as this:

Some[Symbol.extract] = (value, ref x) => {
    if (!(value instanceof Some)) {
        throw new ReferenceError()
    }
    x = value._value
}

Pattern matching could be similar, just you'd need to return a boolean on if a match was made.

I'm pretty sure there's a better way of modeling this, but I do suspect references could bring garbage down to a minimum (making it more useful in low-resource and performance-sensitive scenarios).

dead-claudia avatar Oct 17 '18 08:10 dead-claudia

C# supports something similar for user-defined destructuring: https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct#deconstructing-user-defined-types. The ES equivalent of the Person example might be something like this (using ref, in place of out):

class Person {
  ...
  [Symbol.deconstruct](ref fname, ref lname) {
    fname = this.FirstName;
    lname = this.LastName;
  }
}

const [fname, lname] = new Person("Bob", "Smith");

(Though I'm not proposing we consider user-defined destructuring.)

rbuckton avatar Aug 25 '20 19:08 rbuckton