BinaryExpression.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = extractValueFromBinaryExpression;
  6. /**
  7. * Extractor function for a BinaryExpression type value node.
  8. * A binary expression has a left and right side separated by an operator
  9. * such as `a + b`.
  10. *
  11. * @param - value - AST Value object with type `BinaryExpression`
  12. * @returns - The extracted value converted to correct type.
  13. */
  14. function extractValueFromBinaryExpression(value) {
  15. // eslint-disable-next-line global-require
  16. var getValue = require('./index.js').default;
  17. var operator = value.operator,
  18. left = value.left,
  19. right = value.right;
  20. var leftVal = getValue(left);
  21. var rightVal = getValue(right);
  22. switch (operator) {
  23. case '==':
  24. return leftVal == rightVal; // eslint-disable-line
  25. case '!=':
  26. return leftVal != rightVal; // eslint-disable-line
  27. case '===':
  28. return leftVal === rightVal;
  29. case '!==':
  30. return leftVal !== rightVal;
  31. case '<':
  32. return leftVal < rightVal;
  33. case '<=':
  34. return leftVal <= rightVal;
  35. case '>':
  36. return leftVal > rightVal;
  37. case '>=':
  38. return leftVal >= rightVal;
  39. case '<<':
  40. return leftVal << rightVal; // eslint-disable-line no-bitwise
  41. case '>>':
  42. return leftVal >> rightVal; // eslint-disable-line no-bitwise
  43. case '>>>':
  44. return leftVal >>> rightVal; // eslint-disable-line no-bitwise
  45. case '+':
  46. return leftVal + rightVal;
  47. case '-':
  48. return leftVal - rightVal;
  49. case '*':
  50. return leftVal * rightVal;
  51. case '/':
  52. return leftVal / rightVal;
  53. case '%':
  54. return leftVal % rightVal;
  55. case '|':
  56. return leftVal | rightVal; // eslint-disable-line no-bitwise
  57. case '^':
  58. return leftVal ^ rightVal; // eslint-disable-line no-bitwise
  59. case '&':
  60. return leftVal & rightVal; // eslint-disable-line no-bitwise
  61. case 'in':
  62. try {
  63. return leftVal in rightVal;
  64. } catch (err) {
  65. return false;
  66. }
  67. case 'instanceof':
  68. if (typeof rightVal !== 'function') {
  69. return false;
  70. }
  71. return leftVal instanceof rightVal;
  72. default:
  73. return undefined;
  74. }
  75. }