Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

polish: skip creating extra reference for safely re-used node #10720

Merged
merged 2 commits into from Nov 16, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -16,14 +16,17 @@ export default declare((api, { loose = false }) => {
return;
}

const ref = scope.generateUidIdentifierBasedOnNode(node.left);
scope.push({ id: ref });
let ref, assignment;
// skip creating extra reference when `left` is semantically safe to re-use
if (t.isIdentifier(node.left)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about using isConstantExpression, or maybe better maybeGenerateMemoised?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea! I end up with maybeGenerateMemoised because it is rare that the left is a literal --even if it is, creating a reference other than inlining this literal should costs less bytes in most situations, given that we generate [_]+ as identifier name for literals.

ref = node.left;
assignment = t.cloneNode(node.left);
} else {
ref = scope.generateUidIdentifierBasedOnNode(node.left);
scope.push({ id: ref });

const assignment = t.assignmentExpression(
"=",
t.cloneNode(ref),
node.left,
);
assignment = t.assignmentExpression("=", t.cloneNode(ref), node.left);
}

path.replaceWith(
t.conditionalExpression(
Expand Down
@@ -0,0 +1,3 @@
function foo(opts) {
var foo = opts ?? {};
}
@@ -0,0 +1,3 @@
{
"plugins": ["proposal-nullish-coalescing-operator"]
}
@@ -0,0 +1,3 @@
function foo(opts) {
var foo = opts !== null && opts !== void 0 ? opts : {};
}
@@ -1 +1 @@
function foo(foo, bar = foo ?? "bar") {}
function foo(foo, qux = foo.bar ?? "qux") {}
@@ -1,3 +1,3 @@
function foo(foo, bar = (_foo = foo) !== null && _foo !== void 0 ? _foo : "bar") {
var _foo;
function foo(foo, qux = (_foo$bar = foo.bar) !== null && _foo$bar !== void 0 ? _foo$bar : "qux") {
var _foo$bar;
}
@@ -0,0 +1 @@
function foo(foo, bar = foo ?? "bar") {}
@@ -0,0 +1,3 @@
{
"plugins": ["proposal-nullish-coalescing-operator"]
}
@@ -0,0 +1 @@
function foo(foo, bar = foo !== null && foo !== void 0 ? foo : "bar") {}