Skip to content
This repository was archived by the owner on Mar 23, 2024. It is now read-only.

Commit ca2ea32

Browse files
hzoomikesherov
authored andcommitted
requireCurlyBraces: use tokenAssert methods
- cleanup: make similar to disallowCurlyBraces
1 parent 933b4d9 commit ca2ea32

2 files changed

Lines changed: 14 additions & 17 deletions

File tree

lib/rules/require-curly-braces.js

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -67,17 +67,11 @@ module.exports.prototype = {
6767

6868
check: function(file, errors) {
6969

70-
function addError(typeString, node) {
71-
var entity = node;
72-
73-
if (typeString === 'Else') {
74-
entity = file.findPrevToken(
75-
file.getTokenByRangeStart(node.alternate.range[0]),
76-
'Keyword',
77-
'else'
78-
);
79-
}
70+
function isNotABlockStatement(node) {
71+
return node && node.type !== 'BlockStatement';
72+
}
8073

74+
function addError(typeString, entity) {
8175
errors.add(
8276
typeString + ' statement without curly braces',
8377
entity.loc.start.line,
@@ -87,7 +81,7 @@ module.exports.prototype = {
8781

8882
function checkBody(type, typeString) {
8983
file.iterateNodesByType(type, function(node) {
90-
if (node.body.type !== 'BlockStatement') {
84+
if (isNotABlockStatement(node.body)) {
9185
addError(typeString, node);
9286
}
9387
});
@@ -97,14 +91,12 @@ module.exports.prototype = {
9791

9892
if (typeIndex['if'] || typeIndex['else']) {
9993
file.iterateNodesByType('IfStatement', function(node) {
100-
if (typeIndex.if && node.consequent.type !== 'BlockStatement') {
94+
if (typeIndex['if'] && isNotABlockStatement(node.consequent)) {
10195
addError('If', node);
10296
}
103-
if (typeIndex['else'] && node.alternate &&
104-
node.alternate.type !== 'BlockStatement' &&
105-
node.alternate.type !== 'IfStatement'
106-
) {
107-
addError('Else', node);
97+
if (typeIndex['else'] && isNotABlockStatement(node.alternate) &&
98+
node.alternate.type !== 'IfStatement') {
99+
addError('Else', file.getPrevToken(file.getFirstNodeToken(node.alternate)));
108100
}
109101
});
110102
}

test/rules/require-curly-braces.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,9 @@ describe('rules/require-curly-braces', function() {
153153
assert(error.line === 4);
154154
assert(error.column === 12);
155155
});
156+
157+
it('should not report missing `else` braces for `else if`', function() {
158+
checker.configure({ requireCurlyBraces: ['else'] });
159+
assert(checker.checkString('if (x) { x++; } else if (x) { x++; }').isEmpty());
160+
});
156161
});

0 commit comments

Comments
 (0)