summaryrefslogtreecommitdiff
path: root/node_modules/babel-plugin-minify-flip-comparisons/lib/index.js
blob: 47820515e818ec1d48ce0e744a737cfe59412558 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"use strict";

module.exports = function ({
  types: t
}) {
  const isVoid0 = require("babel-helper-is-void-0")(t);

  return {
    name: "minify-flip-comparisons",
    visitor: {
      // flip comparisons with a pure right hand value, this ensures
      // consistency with comparisons and increases the length of
      // strings that gzip can match
      // typeof blah === 'function' -> 'function' === typeof blah
      BinaryExpression(path) {
        const node = path.node;
        const right = node.right,
              left = node.left; // Make sure we have a constant on the right.

        if (!t.isLiteral(right) && !isVoid0(right) && !(t.isUnaryExpression(right) && t.isLiteral(right.argument)) && !t.isObjectExpression(right) && !t.isArrayExpression(right)) {
          return;
        } // Commutative operators.


        if (t.EQUALITY_BINARY_OPERATORS.indexOf(node.operator) >= 0 || ["*", "^", "&", "|"].indexOf(node.operator) >= 0) {
          node.left = right;
          node.right = left;
          return;
        }

        if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(node.operator) >= 0) {
          node.left = right;
          node.right = left;
          let operator;

          switch (node.operator) {
            case ">":
              operator = "<";
              break;

            case "<":
              operator = ">";
              break;

            case ">=":
              operator = "<=";
              break;

            case "<=":
              operator = ">=";
              break;
          }

          node.operator = operator;
          return;
        }
      }

    }
  };
};