Skip to content

Commit

Permalink
fix(no-conditional-statements): allow continue and break statements w…
Browse files Browse the repository at this point in the history
…ith labels to be considered "returning"
  • Loading branch information
RebeccaStevens committed Jul 11, 2024
1 parent b83aa68 commit 711bab1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/rules/no-conditional-statements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
isContinueStatement,
isExpressionStatement,
isIfStatement,
isLabeledStatement,
isReturnStatement,
isSwitchStatement,
isThrowStatement,
Expand Down Expand Up @@ -195,18 +196,6 @@ function getIfBranchViolations(
return violations.flatMap(incompleteBranchViolation);
}

/**
* Is the given statement, when inside a switch statement, a returning branch?
*/
function isSwitchReturningBranch(statement: TSESTree.Statement) {
return (
// Another instance of this rule will check nested switch statements.
isSwitchStatement(statement) ||
isReturnStatement(statement) ||
isThrowStatement(statement)
);
}

/**
* Get all of the violations in the given switch statement assuming switch
* statements are allowed.
Expand All @@ -217,6 +206,8 @@ function getSwitchViolations(
): RuleResult<keyof typeof errorMessages, Options>["descriptors"] {
const isNeverExpressions = getIsNeverExpressions(context);

const label = isLabeledStatement(node.parent) ? node.parent.label.name : null;

const violations = node.cases.filter((branch) => {
if (branch.consequent.length === 0) {
return false;
Expand All @@ -241,6 +232,22 @@ function getSwitchViolations(
});

return violations.flatMap(incompleteBranchViolation);

/**
* Is the given statement, when inside a switch statement, a returning branch?
*/
function isSwitchReturningBranch(statement: TSESTree.Statement) {
return (
// Another instance of this rule will check nested switch statements.
isSwitchStatement(statement) ||
isReturnStatement(statement) ||
isThrowStatement(statement) ||
(isBreakStatement(statement) &&
statement.label !== null &&
statement.label.name !== label) ||
isContinueStatement(statement)
);
}
}

/**
Expand Down
6 changes: 6 additions & 0 deletions src/utils/type-guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ export function isIfStatement(
return node.type === AST_NODE_TYPES.IfStatement;
}

export function isLabeledStatement(
node: TSESTree.Node,
): node is TSESTree.LabeledStatement {
return node.type === AST_NODE_TYPES.LabeledStatement;
}

export function isMemberExpression(
node: TSESTree.Node,
): node is TSESTree.MemberExpression {
Expand Down

0 comments on commit 711bab1

Please sign in to comment.