Skip to content

Commit

Permalink
Make only-arrow-functions allow functions with a this parameter (pa…
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-hanson authored and nchen63 committed Nov 23, 2016
1 parent 69c4674 commit e0869e4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/rules/onlyArrowFunctionsRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,31 @@ export class Rule extends Lint.Rules.AbstractRule {

class OnlyArrowFunctionsWalker extends Lint.RuleWalker {
public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
if (!node.asteriskToken && !this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
if (!this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
this.failUnlessExempt(node);
}
super.visitFunctionDeclaration(node);
}

public visitFunctionExpression(node: ts.FunctionExpression) {
if (!node.asteriskToken) {
this.failUnlessExempt(node);
super.visitFunctionExpression(node);
}

private failUnlessExempt(node: ts.FunctionLikeDeclaration) {
if (!functionIsExempt(node)) {
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
}
super.visitFunctionExpression(node);
}
}

/** Generator functions and functions explicitly declaring `this` are allowed. */
function functionIsExempt(node: ts.FunctionLikeDeclaration) {
return node.asteriskToken || hasThisParameter(node);
}

function hasThisParameter(node: ts.FunctionLikeDeclaration) {
const first = node.parameters[0];
return first && first.name.kind === ts.SyntaxKind.Identifier &&
(first.name as ts.Identifier).originalKeywordKind === ts.SyntaxKind.ThisKeyword;
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,7 @@ function () {
function* generator() {}
let generator = function*() {}

function hasThisParameter(this) {}
let hasThisParameter = function(this) {}

[0]: non-arrow functions are forbidden
3 changes: 3 additions & 0 deletions test/rules/only-arrow-functions/default/test.ts.lint
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ function () {
function* generator() {}
let generator = function*() {}

function hasThisParameter(this) {}
let hasThisParameter = function(this) {}

[0]: non-arrow functions are forbidden

0 comments on commit e0869e4

Please sign in to comment.