guard-for-in.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. docs: {
  12. description: "require `for-in` loops to include an `if` statement",
  13. category: "Best Practices",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/guard-for-in"
  16. },
  17. schema: []
  18. },
  19. create(context) {
  20. return {
  21. ForInStatement(node) {
  22. const body = node.body;
  23. // empty statement
  24. if (body.type === "EmptyStatement") {
  25. return;
  26. }
  27. // if statement
  28. if (body.type === "IfStatement") {
  29. return;
  30. }
  31. // empty block
  32. if (body.type === "BlockStatement" && body.body.length === 0) {
  33. return;
  34. }
  35. // block with just if statement
  36. if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
  37. return;
  38. }
  39. // block that starts with if statement
  40. if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
  41. const i = body.body[0];
  42. // ... whose consequent is a continue
  43. if (i.consequent.type === "ContinueStatement") {
  44. return;
  45. }
  46. // ... whose consequent is a block that contains only a continue
  47. if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
  48. return;
  49. }
  50. }
  51. context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." });
  52. }
  53. };
  54. }
  55. };