Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions rules/earlyExitRule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isBlock, isCaseOrDefaultClause, isIfStatement, isFunctionScopeBoundary } from 'tsutils';
import { isBlock, isThrowStatement, isCaseOrDefaultClause, isIfStatement, isFunctionScopeBoundary } from 'tsutils';
import * as Lint from 'tslint';
import * as ts from 'typescript';

Expand Down Expand Up @@ -52,7 +52,7 @@ function walk(ctx: Lint.WalkContext<IOptions>) {
const thenSize = size(thenStatement, sourceFile);

if (elseStatement === undefined) {
if (isLarge(thenSize))
if (isLarge(thenSize) && !isThrow(thenStatement))
fail(failureString(exit));
return;
}
Expand Down Expand Up @@ -92,6 +92,14 @@ function size(node: ts.Node, sourceFile: ts.SourceFile): number {
: diff(node.getStart(sourceFile), node.end, sourceFile);
}

function isThrow(node: ts.Node): boolean {
return isBlock(node)
? node.statements.length === 1
? isThrowStatement(node.statements[0])
: false
: isThrowStatement(node);
}

function diff(start: number, end: number, sourceFile: ts.SourceFile): number {
return ts.getLineAndCharacterOfPosition(sourceFile, end).line
- ts.getLineAndCharacterOfPosition(sourceFile, start).line
Expand Down
8 changes: 8 additions & 0 deletions test/rules/early-exit/throwing-is-early-exit/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Foo {
f(a) {
if (a === undefined) {
throw new Error("a is undefined");
}
}
}

6 changes: 6 additions & 0 deletions test/rules/early-exit/throwing-is-early-exit/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rulesDirectory": "../../../../rules",
"rules": {
"early-exit": true
}
}