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.

guard-for-in.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @fileoverview Rule to flag for-in loops without if statements inside
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "require `for-in` loops to include an `if` statement",
  14. category: "Best Practices",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/guard-for-in"
  17. },
  18. schema: []
  19. },
  20. create(context) {
  21. return {
  22. ForInStatement(node) {
  23. const body = node.body;
  24. // empty statement
  25. if (body.type === "EmptyStatement") {
  26. return;
  27. }
  28. // if statement
  29. if (body.type === "IfStatement") {
  30. return;
  31. }
  32. // empty block
  33. if (body.type === "BlockStatement" && body.body.length === 0) {
  34. return;
  35. }
  36. // block with just if statement
  37. if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
  38. return;
  39. }
  40. // block that starts with if statement
  41. if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
  42. const i = body.body[0];
  43. // ... whose consequent is a continue
  44. if (i.consequent.type === "ContinueStatement") {
  45. return;
  46. }
  47. // ... whose consequent is a block that contains only a continue
  48. if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
  49. return;
  50. }
  51. }
  52. context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." });
  53. }
  54. };
  55. }
  56. };