no-negated-condition.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @fileoverview Rule to disallow a negated condition
  3. * @author Alberto Rodríguez
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "disallow negated conditions",
  13. category: "Stylistic Issues",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/no-negated-condition"
  16. },
  17. schema: []
  18. },
  19. create(context) {
  20. /**
  21. * Determines if a given node is an if-else without a condition on the else
  22. * @param {ASTNode} node The node to check.
  23. * @returns {boolean} True if the node has an else without an if.
  24. * @private
  25. */
  26. function hasElseWithoutCondition(node) {
  27. return node.alternate && node.alternate.type !== "IfStatement";
  28. }
  29. /**
  30. * Determines if a given node is a negated unary expression
  31. * @param {Object} test The test object to check.
  32. * @returns {boolean} True if the node is a negated unary expression.
  33. * @private
  34. */
  35. function isNegatedUnaryExpression(test) {
  36. return test.type === "UnaryExpression" && test.operator === "!";
  37. }
  38. /**
  39. * Determines if a given node is a negated binary expression
  40. * @param {Test} test The test to check.
  41. * @returns {boolean} True if the node is a negated binary expression.
  42. * @private
  43. */
  44. function isNegatedBinaryExpression(test) {
  45. return test.type === "BinaryExpression" &&
  46. (test.operator === "!=" || test.operator === "!==");
  47. }
  48. /**
  49. * Determines if a given node has a negated if expression
  50. * @param {ASTNode} node The node to check.
  51. * @returns {boolean} True if the node has a negated if expression.
  52. * @private
  53. */
  54. function isNegatedIf(node) {
  55. return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
  56. }
  57. return {
  58. IfStatement(node) {
  59. if (!hasElseWithoutCondition(node)) {
  60. return;
  61. }
  62. if (isNegatedIf(node)) {
  63. context.report({ node, message: "Unexpected negated condition." });
  64. }
  65. },
  66. ConditionalExpression(node) {
  67. if (isNegatedIf(node)) {
  68. context.report({ node, message: "Unexpected negated condition." });
  69. }
  70. }
  71. };
  72. }
  73. };