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

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