Skip to content

Commit

Permalink
feature(eslint-plugin-putout) single-property.js (https://gist.github…
Browse files Browse the repository at this point in the history
  • Loading branch information
coderaiser committed Oct 27, 2019
1 parent ab0adc0 commit e3e38ed
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 0 deletions.
53 changes: 53 additions & 0 deletions packages/eslint-plugin-putout/rules/single-property.js
@@ -0,0 +1,53 @@
'use strict';

module.exports = {
meta: {
type: 'layout',
docs: {
description: 'Keep curly braces on one line when you have one destructuring property',
category: 'destructuring',
recommended: true,
},
fixable: 'whitespace',
},

create(context) {
return {
'VariableDeclarator[id.type="ObjectPattern"][id.properties.length=1]': (node) => {
const {id} = node;

const text = context
.getSourceCode()
.getText(node.parent);

if (!/(const|let|var) \{\n/.test(text))
return;

const assignRegExp = /\{\n?.*=.*\n?.*}/;

if (assignRegExp.test(text))
return;

context.report({
node,
message: 'Keep curly braces on one line when you have one destructuring property',

fix(fixer) {
const [property] = id.properties;
const {key, value} = property;

if (key.name === value.name)
return [
fixer.replaceText(id, `{${key.name}}`),
];

return [
fixer.replaceText(id, `{${key.name}: ${value.name}}`),
];
},
});
},
};
},
};

22 changes: 22 additions & 0 deletions packages/eslint-plugin-putout/rules/single-property.md
@@ -0,0 +1,22 @@
# keep curly bracesin in one line when property is single (single-property-destructuring)

When `putout` removes unused variables declared as destructured properties, it keeps one property to take 3 lines, instead of 1.

## Rule Details

This rule aims to shorten destricturing of one property.

Examples of **incorrect** code for this rule:

```js
const {
username
} = user;
```

Examples of **correct** code for this rule:

```js
const {username} = user;
```

37 changes: 37 additions & 0 deletions packages/eslint-plugin-putout/rules/single-property.spec.js
@@ -0,0 +1,37 @@
'use strict';

const rule = require('./single-property-destructuring');
const {RuleTester} = require('eslint');

const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2019,
},
});

ruleTester.run('single-property-destructuring', rule, {
valid: [
`const {hello} = world;`,
`const {hello} = get({});`,
`const {
hello = true
} = world;`,
],

invalid: [{
code: `const {\n hello\n} = world`,
output: 'const {hello} = world',
errors: [{
message: 'Keep curly braces on one line when you have one destructuring property',
type: 'VariableDeclarator',
}],
}, {
code: `const {\n hello: h\n} = world`,
output: 'const {hello: h} = world',
errors: [{
message: 'Keep curly braces on one line when you have one destructuring property',
type: 'VariableDeclarator',
}],
}],
});

0 comments on commit e3e38ed

Please sign in to comment.