Skip to content

Commit

Permalink
Do not unpack array patterns that update a referenced binding
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Aug 30, 2018
1 parent 15f4566 commit ba94037
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 8 deletions.
32 changes: 24 additions & 8 deletions packages/babel-plugin-transform-destructuring/src/index.js
Expand Up @@ -44,13 +44,23 @@ export default declare((api, options) => {
return false;
}

const arrayUnpackVisitor = {
ReferencedIdentifier(path, state) {
if (state.bindings[path.node.name]) {
state.deopt = true;
path.stop();
}
},
const STOP_TRAVERSAL = {};

// NOTE: This visitor is meant to be used via t.traverse
const arrayUnpackVisitor = (node, ancestors, state) => {
if (!ancestors.length) {
// Top-level node: this is the array literal.
return;
}

if (
t.isIdentifier(node) &&
t.isReferenced(node, ancestors[ancestors.length - 1]) &&
state.bindings[node.name]
) {
state.deopt = true;
throw STOP_TRAVERSAL;
}
};

class DestructuringTransformer {
Expand Down Expand Up @@ -282,7 +292,13 @@ export default declare((api, options) => {
// deopt on reference to left side identifiers
const bindings = t.getBindingIdentifiers(pattern);
const state = { deopt: false, bindings };
this.scope.traverse(arr, arrayUnpackVisitor, state);

try {
t.traverse(arr, arrayUnpackVisitor, state);
} catch (e) {
if (e !== STOP_TRAVERSAL) throw e;
}

return !state.deopt;
}

Expand Down
@@ -0,0 +1,4 @@
function isBetween(x, a, b) {
if (a > b) [a, b] = [b, a];
return x > a && x < b;
}
@@ -0,0 +1,3 @@
{
"plugins": ["transform-destructuring"]
}
@@ -0,0 +1,9 @@
function isBetween(x, a, b) {
if (a > b) {
var _ref = [b, a];
a = _ref[0];
b = _ref[1];
}

return x > a && x < b;
}

0 comments on commit ba94037

Please sign in to comment.