Extensible destructuring proposal

Bergi a.d.bergi at web.de
Tue Jul 21 14:23:39 UTC 2015


Samuel Hapák schrieb:

> The main idea is, that if object defines `Symbol.get` method, it gets used to access properties of object instead of `[]` when destructuring.

Aw, when I read "extensible destructuring" I had hoped to see an 
extension to the destructuring syntax, not to see how semantics of 
destructuring objects are changed.

What do you think about extractor functions, like in Scala 
<http://www.scala-lang.org/old/node/112>?
Instead of `unapply` or `unapplySeq` methods we'd probably use an 
`@@extractor` (`Symbol.extractor`) method or so, allowing us to do

     let Map({a, b, c}) = myMap;

     let List(a, b, c) = myList;

     const Map({author: Map({name: {first, last}, birthdate})}) = book;

which would desugar to

     let [{a, b, c}] = Map[Symbol.extractor](myMap);

     let [a, b, c] = List[Symbol.extractor](myList);

     const [{author: __author}] = Map[Symbol.extractor](book);
     const [{name: {first, last}, birthdate}] = 
Map[Symbol.extractor](__author);

where each extractor method would return an Iterable that is assigned to 
the "arguments" of the extractor. (A Proxy to lazily destructure object 
literals in there is a good idea, thanks @Claude).

This would even allow us to call functions on destructuring, think about 
module imports:

     // a.js
     export default function factory(options) {
         …
         return moduleInstance;
     }

     // b.js
     const NoOptions = {
         [Symbol.extractor](factory) { return [factory()]; }
     };
     const WithOptions = (...args) => ({
         [Symbol.extractor](factory) { return [factory(...args)]; }
     });

     import NoOptions(A) from "a";
     import WithOptions("config")(A) from "a";
     // A === moduleInstance

What do you think about that?

  Bergi


More information about the es-discuss mailing list