Skip to content

Commit e0869e4

Browse files
andy-hansonnchen63
authored andcommitted
Make only-arrow-functions allow functions with a this parameter (palantir#1597)
1 parent 69c4674 commit e0869e4

File tree

3 files changed

+25
-4
lines changed

3 files changed

+25
-4
lines changed

src/rules/onlyArrowFunctionsRule.ts

+19-4
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,31 @@ export class Rule extends Lint.Rules.AbstractRule {
5656

5757
class OnlyArrowFunctionsWalker extends Lint.RuleWalker {
5858
public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
59-
if (!node.asteriskToken && !this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
60-
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
59+
if (!this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
60+
this.failUnlessExempt(node);
6161
}
6262
super.visitFunctionDeclaration(node);
6363
}
6464

6565
public visitFunctionExpression(node: ts.FunctionExpression) {
66-
if (!node.asteriskToken) {
66+
this.failUnlessExempt(node);
67+
super.visitFunctionExpression(node);
68+
}
69+
70+
private failUnlessExempt(node: ts.FunctionLikeDeclaration) {
71+
if (!functionIsExempt(node)) {
6772
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
6873
}
69-
super.visitFunctionExpression(node);
7074
}
7175
}
76+
77+
/** Generator functions and functions explicitly declaring `this` are allowed. */
78+
function functionIsExempt(node: ts.FunctionLikeDeclaration) {
79+
return node.asteriskToken || hasThisParameter(node);
80+
}
81+
82+
function hasThisParameter(node: ts.FunctionLikeDeclaration) {
83+
const first = node.parameters[0];
84+
return first && first.name.kind === ts.SyntaxKind.Identifier &&
85+
(first.name as ts.Identifier).originalKeywordKind === ts.SyntaxKind.ThisKeyword;
86+
}

test/rules/only-arrow-functions/allow-declarations/test.ts.lint

+3
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,7 @@ function () {
2020
function* generator() {}
2121
let generator = function*() {}
2222

23+
function hasThisParameter(this) {}
24+
let hasThisParameter = function(this) {}
25+
2326
[0]: non-arrow functions are forbidden

test/rules/only-arrow-functions/default/test.ts.lint

+3
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,7 @@ function () {
2323
function* generator() {}
2424
let generator = function*() {}
2525

26+
function hasThisParameter(this) {}
27+
let hasThisParameter = function(this) {}
28+
2629
[0]: non-arrow functions are forbidden

0 commit comments

Comments
 (0)