forked from sindresorhus/eslint-plugin-unicorn
/
empty-brace-spaces.js
58 lines (52 loc) · 1.5 KB
/
empty-brace-spaces.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict';
const {isOpeningBraceToken} = require('eslint-utils');
const {matches} = require('./selectors/index.js');
const MESSAGE_ID = 'empty-brace-spaces';
const messages = {
[MESSAGE_ID]: 'Do not add spaces between braces.',
};
const selector = matches([
'BlockStatement[body.length=0]',
'ClassBody[body.length=0]',
'ObjectExpression[properties.length=0]',
'StaticBlock[body.length=0]',
// Experimental https://github.com/tc39/proposal-record-tuple
'RecordExpression[properties.length=0]',
]);
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => ({
[selector](node) {
const sourceCode = context.getSourceCode();
const filter = node.type === 'RecordExpression'
? token => token.type === 'Punctuator' && (token.value === '#{' || token.value === '{|')
: isOpeningBraceToken;
const openingBrace = sourceCode.getFirstToken(node, {filter});
const closingBrace = sourceCode.getLastToken(node);
const [, start] = openingBrace.range;
const [end] = closingBrace.range;
const textBetween = sourceCode.text.slice(start, end);
if (!/^\s+$/.test(textBetween)) {
return;
}
return {
loc: {
start: openingBrace.loc.end,
end: closingBrace.loc.start,
},
messageId: MESSAGE_ID,
fix: fixer => fixer.removeRange([start, end]),
};
},
});
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'layout',
docs: {
description: 'Enforce no spaces between braces.',
},
fixable: 'whitespace',
messages,
},
};