Skip to content
This repository has been archived by the owner on Jul 15, 2023. It is now read-only.

Expand prefer-array-literal rule #842

Merged
merged 2 commits into from
Mar 21, 2019
Merged
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
9 changes: 9 additions & 0 deletions src/preferArrayLiteralRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class Rule extends Lint.Rules.AbstractRule {

public static GENERICS_FAILURE_STRING: string = 'Replace generic-typed Array with array literal: ';
public static CONSTRUCTOR_FAILURE_STRING: string = 'Replace Array constructor with an array literal: ';
public static FUNCTION_FAILURE_STRING: string = 'Replace Array function with an array literal: ';

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions()));
Expand Down Expand Up @@ -77,6 +78,14 @@ function walk(ctx: Lint.WalkContext<Options>) {
}
}

if (tsutils.isCallExpression(node)) {
const expr = node.expression;
if (expr.getText() === 'Array') {
const failureString = Rule.FUNCTION_FAILURE_STRING + node.getText();
ctx.addFailureAt(node.getStart(), node.getWidth(), failureString);
}
}

return ts.forEachChild(node, cb);
}

Expand Down
4 changes: 2 additions & 2 deletions src/tests/ReactA11yTitlesRuleTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('reactA11yTitlesRule', (): void => {
});

it('should fail on longer than 60 charactes title', (): void => {
const title: string = Array(61).join('a');
const title: string = 'a'.repeat(60);
const script: string = `
import React = require('react');

Expand All @@ -70,7 +70,7 @@ describe('reactA11yTitlesRule', (): void => {
});

it('should pass on shorter than 60 characters title', (): void => {
const title: string = Array(5).join('a');
const title: string = 'a'.repeat(5);
const script: string = `
import React = require('react');

Expand Down
12 changes: 12 additions & 0 deletions src/tests/preferArrayLiteralRuleTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,16 @@ describe('preferArrayLiteralRule', (): void => {
}
]);
});

it('should ban Array function', (): void => {
const inputScript: string = 'Array(2)';
TestHelper.assertViolations(ruleName, inputScript, [
{
failure: 'Replace Array function with an array literal: Array(2)',
name: Utils.absolutePath('file.ts'),
ruleName: 'prefer-array-literal',
startPosition: { character: 1, line: 1 }
}
]);
});
});