Skip to content

Commit

Permalink
Replace x != undefined with x != null (#572)
Browse files Browse the repository at this point in the history
* Replace `x != undefined` with `x != null`

* Create eqnull-test.js

* Minify `null != null`, `undefined == null`, etc.

* Test undefined == undefined

* Include babel-types

* Fix a typo

* Semicolons in tests

* Remove unused require

* Node 4 support

* npm run format

* Remove unwanted transform

* 🔥 unused variable

* `void <something>` is `undefined` too

* Restore eqnull-test.js

* Only include pure `void` expressions

* Fix scope

* npm run format

* Remove unused `unpad`

* Transform `undefined` to `null` on both sides of the ==

* thePlugin

* Check if there’s a variable named `undefined` before transforming

* t.isFoo(path.node) → path.isFoo()

* npm run format

* 🔥 undefinedToNull returns

* Move the feature to simplify

* Use test fixtures
  • Loading branch information
j-f1 authored and boopathi committed May 14, 2018
1 parent 18dcfe1 commit 540d75e
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
x == undefined;
x == void 0;
x === undefined;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
x == null, x == null, x === undefined;
24 changes: 24 additions & 0 deletions packages/babel-plugin-minify-simplify/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ module.exports = ({ types: t }) => {
]
},

BinaryExpression(path) {
if (["!=", "=="].indexOf(path.node.operator) !== -1) {
undefinedToNull(path.get("left"));
undefinedToNull(path.get("right"));
}
},

LogicalExpression: {
exit: logicalExpression.simplifyPatterns
},
Expand Down Expand Up @@ -1141,4 +1148,21 @@ module.exports = ({ types: t }) => {
function isAncestor(path1, path2) {
return !!path2.findParent(parent => parent === path1);
}

function isPureVoid(path) {
return path.isUnaryExpression({ operator: "void" }) && path.isPure();
}

function isGlobalUndefined(path) {
return (
path.isIdentifier({ name: "undefined" }) &&
!path.scope.getBinding("undefined")
);
}

function undefinedToNull(path) {
if (isGlobalUndefined(path) || isPureVoid(path)) {
path.replaceWith(t.nullLiteral());
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ module.exports = function({ types: t }) {
BinaryExpression(path) {
const { node } = path;
const op = node.operator;

if (op !== "===" && op !== "!==") {
return;
}
Expand Down

0 comments on commit 540d75e

Please sign in to comment.