Transformation Operations·续1

- function square(n) {-   return n * n;- }

Replacing a parent" class="reference-link">Replacing a parent

Just call replaceWith with the parentPath: path.parentPath

BinaryExpression(path) {  path.parentPath.replaceWith(    t.expressionStatement(t.stringLiteral("Anyway the wind blows, doesn't really matter to me, to me."))  );}
  function square(n) {-   return n * n;+   "Anyway the wind blows, doesn't really matter to me, to me.";  }

Removing a parent" class="reference-link">Removing a parent

BinaryExpression(path) {  path.parentPath.remove();}
  function square(n) {-   return n * n;  }

Scope" class="reference-link">Scope

Checking if a local variable is bound" class="reference-link">Checking if a local variable is bound

FunctionDeclaration(path) {  if (path.scope.hasBinding("n")) {    // ...  }}

This will walk up the scope tree and check for that particular binding.

You can also check if a scope has its own binding:

FunctionDeclaration(path) {  if (path.scope.hasOwnBinding("n")) {    // ...  }}

Generating a UID" class="reference-link">Generating a UID

This will generate an identifier that doesn’t collide with any locally defined variables.

FunctionDeclaration(path) {  path.scope.generateUidIdentifier("uid");  // Node { type: "Identifier", name: "_uid" }  path.scope.generateUidIdentifier("uid");  // Node { type: "Identifier", name: "_uid2" }}

Pushing a variable declaration to a parent scope" class="reference-link">Pushing a variable declaration to a parent scope

Sometimes you may want to push a VariableDeclaration so you can assign to it.

FunctionDeclaration(path) {  const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id);  path.remove();  path.scope.parent.push({ id, init: path.node });}
- function square(n) {+ var _square = function square(n) {    return n * n;- }+ };

Rename a binding and its references" class="reference-link">Rename a binding and its references

FunctionDeclaration(path) {  path.scope.rename("n", "x");}
- function square(n) {-   return n * n;+ function square(x) {+   return x * x;  }

Alternatively, you can rename a binding to a generated unique identifier:

FunctionDeclaration(path) {  path.scope.rename("n");}
- function square(n) {-   return n * n;+ function square(_n) {+   return _n * _n;  }