Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-negated-condition.js 2.7KB

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