prefer-while.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. /*
  3. * eslint-plugin-sonarjs
  4. * Copyright (C) 2018-2021 SonarSource SA
  5. * mailto:info AT sonarsource DOT com
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. */
  21. // https://sonarsource.github.io/rspec/#/rspec/S1264
  22. const docs_url_1 = require("../utils/docs-url");
  23. const rule = {
  24. meta: {
  25. messages: {
  26. replaceForWithWhileLoop: 'Replace this "for" loop with a "while" loop.',
  27. },
  28. schema: [],
  29. type: 'suggestion',
  30. docs: {
  31. description: 'A "while" loop should be used instead of a "for" loop',
  32. recommended: 'error',
  33. url: (0, docs_url_1.default)(__filename),
  34. },
  35. fixable: 'code',
  36. },
  37. create(context) {
  38. return {
  39. ForStatement(node) {
  40. const forLoop = node;
  41. const forKeyword = context.getSourceCode().getFirstToken(node);
  42. if (!forLoop.init && !forLoop.update && forLoop.test && forKeyword) {
  43. context.report({
  44. messageId: `replaceForWithWhileLoop`,
  45. loc: forKeyword.loc,
  46. fix: getFix(forLoop),
  47. });
  48. }
  49. },
  50. };
  51. function getFix(forLoop) {
  52. const forLoopRange = forLoop.range;
  53. const closingParenthesisToken = context.getSourceCode().getTokenBefore(forLoop.body);
  54. const condition = forLoop.test;
  55. if (condition && forLoopRange && closingParenthesisToken) {
  56. return (fixer) => {
  57. const start = forLoopRange[0];
  58. const end = closingParenthesisToken.range[1];
  59. const conditionText = context.getSourceCode().getText(condition);
  60. return fixer.replaceTextRange([start, end], `while (${conditionText})`);
  61. };
  62. }
  63. return undefined;
  64. }
  65. },
  66. };
  67. module.exports = rule;
  68. //# sourceMappingURL=prefer-while.js.map