Skip to content

Compound destructuring

Rich Harris requested to merge compound-destructuring into master

Code like var { a: { b: c }, d: { e: f, g: h } } = x() is terrible and you should never, ever write it, but it's valid ES2015 without size or performance hazards, so we should support it. This PR allows arbitrarily complex destructuring.

For array patterns, the result is more similar to Babel's es2015-loose than es2015 because that's what you want in the vast majority of situations – though we could support the stricter version in future if we really wanted to:

// in
var [[[a]], [[b, c = 1]]] = x;

// out
var a = x[0][0][0];
var x_1_0 = x[1][0];
var b = x_1_0[0];
var c = x_1_0[1]; if ( c === void 0 ) c = 1;

// Babel es2015-loose
var _x = x;
var _x$ = _x[0];
var _x$$ = _x$[0];
var a = _x$$[0];
var _x$2 = _x[1];
var _x$2$ = _x$2[0];
var b = _x$2$[0];
var _x$2$$ = _x$2$[1];
var c = _x$2$$ === undefined ? 1 : _x$2$$;

// Babel es2015
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _x = x;

var _x2 = _slicedToArray(_x, 2);

var _x2$ = _slicedToArray(_x2[0], 1);

var _x2$$ = _slicedToArray(_x2$[0], 1);

var a = _x2$$[0];

var _x2$2 = _slicedToArray(_x2[1], 1);

var _x2$2$ = _slicedToArray(_x2$2[0], 2);

var b = _x2$2$[0];
var _x2$2$$ = _x2$2$[1];
var c = _x2$2$$ === undefined ? 1 : _x2$2$$;

Merge request reports