no-nested-ternary.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. const {isParenthesized} = require('@eslint-community/eslint-utils');
  3. const MESSAGE_ID_TOO_DEEP = 'too-deep';
  4. const MESSAGE_ID_SHOULD_PARENTHESIZED = 'should-parenthesized';
  5. const messages = {
  6. [MESSAGE_ID_TOO_DEEP]: 'Do not nest ternary expressions.',
  7. [MESSAGE_ID_SHOULD_PARENTHESIZED]: 'Nest ternary expression should be parenthesized.',
  8. };
  9. const nestTernarySelector = level => `:not(ConditionalExpression)${' > ConditionalExpression'.repeat(level)}`;
  10. /** @param {import('eslint').Rule.RuleContext} context */
  11. const create = context => {
  12. const sourceCode = context.getSourceCode();
  13. return {
  14. [nestTernarySelector(3)]: node =>
  15. // Nesting more than one level not allowed.
  16. ({node, messageId: MESSAGE_ID_TOO_DEEP}),
  17. [nestTernarySelector(2)](node) {
  18. if (!isParenthesized(node, sourceCode)) {
  19. return {
  20. node,
  21. messageId: MESSAGE_ID_SHOULD_PARENTHESIZED,
  22. fix: fixer => [
  23. fixer.insertTextBefore(node, '('),
  24. fixer.insertTextAfter(node, ')'),
  25. ],
  26. };
  27. }
  28. },
  29. };
  30. };
  31. /** @type {import('eslint').Rule.RuleModule} */
  32. module.exports = {
  33. create,
  34. meta: {
  35. type: 'suggestion',
  36. docs: {
  37. description: 'Disallow nested ternary expressions.',
  38. },
  39. fixable: 'code',
  40. messages,
  41. },
  42. };