one-var-declaration-per-line.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @fileoverview Rule to check multiple var declarations per line
  3. * @author Alberto Rodríguez
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "require or disallow newlines around variable declarations",
  13. category: "Stylistic Issues",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/one-var-declaration-per-line"
  16. },
  17. schema: [
  18. {
  19. enum: ["always", "initializations"]
  20. }
  21. ],
  22. fixable: "whitespace"
  23. },
  24. create(context) {
  25. const ERROR_MESSAGE = "Expected variable declaration to be on a new line.";
  26. const always = context.options[0] === "always";
  27. //--------------------------------------------------------------------------
  28. // Helpers
  29. //--------------------------------------------------------------------------
  30. /**
  31. * Determine if provided keyword is a variant of for specifiers
  32. * @private
  33. * @param {string} keyword - keyword to test
  34. * @returns {boolean} True if `keyword` is a variant of for specifier
  35. */
  36. function isForTypeSpecifier(keyword) {
  37. return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
  38. }
  39. /**
  40. * Checks newlines around variable declarations.
  41. * @private
  42. * @param {ASTNode} node - `VariableDeclaration` node to test
  43. * @returns {void}
  44. */
  45. function checkForNewLine(node) {
  46. if (isForTypeSpecifier(node.parent.type)) {
  47. return;
  48. }
  49. const declarations = node.declarations;
  50. let prev;
  51. declarations.forEach(current => {
  52. if (prev && prev.loc.end.line === current.loc.start.line) {
  53. if (always || prev.init || current.init) {
  54. context.report({
  55. node,
  56. message: ERROR_MESSAGE,
  57. loc: current.loc.start,
  58. fix: fixer => fixer.insertTextBefore(current, "\n")
  59. });
  60. }
  61. }
  62. prev = current;
  63. });
  64. }
  65. //--------------------------------------------------------------------------
  66. // Public
  67. //--------------------------------------------------------------------------
  68. return {
  69. VariableDeclaration: checkForNewLine
  70. };
  71. }
  72. };