Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add array-join-separator rule #1284

Merged
merged 7 commits into from
May 18, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
37 changes: 37 additions & 0 deletions docs/rules/array-join-separator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Enforce using the separator argument when concatenating elements in an array
fisker marked this conversation as resolved.
Show resolved Hide resolved

Enforce using [the separator argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join#parameters) when calling [Array#join()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join), it's more obvious what the separator is.
fisker marked this conversation as resolved.
Show resolved Hide resolved

This rule is fixable.

## Fail

```js
const string = array.join();
```

```js
const string = Array.prototype.join.call(arrayLike);
```

```js
const string = [].join.call(arrayLike);
```

## Pass

```js
const string = array.join(',');
```

```js
const string = array.join('|');
```

```js
const string = Array.prototype.join.call(arrayLike, '');
```

```js
const string = [].join.call(arrayLike, '\n');
```
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = {
'unicorn'
],
rules: {
'unicorn/array-join-separator': 'error',
'unicorn/better-regex': 'error',
'unicorn/catch-error-name': 'error',
'unicorn/consistent-destructuring': 'error',
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Configure it in `package.json`.
"unicorn"
],
"rules": {
"unicorn/array-join-separator": "error",
"unicorn/better-regex": "error",
"unicorn/catch-error-name": "error",
"unicorn/consistent-destructuring": "error",
Expand Down Expand Up @@ -132,6 +133,7 @@ Each rule has emojis denoting:

| Name                                          | Description | ✅ | 🔧 |
| :-- | :-- | :-- | :-- |
| [array-join-separator](docs/rules/array-join-separator.md) | Enforce using the separator argument when concatenating elements in an array. | ✅ | 🔧 |
| [better-regex](docs/rules/better-regex.md) | Improve regexes by making them shorter, consistent, and safer. | ✅ | 🔧 |
| [catch-error-name](docs/rules/catch-error-name.md) | Enforce a specific parameter name in catch clauses. | ✅ | 🔧 |
| [consistent-destructuring](docs/rules/consistent-destructuring.md) | Use destructured variables over properties. | ✅ | 🔧 |
Expand Down
104 changes: 104 additions & 0 deletions rules/array-join-separator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use strict';
const {isCommaToken} = require('eslint-utils');
const getDocumentationUrl = require('./utils/get-documentation-url');
const methodSelector = require('./utils/method-selector');

const MESSAGE_ID = 'array-join-separator';
const messages = {
[MESSAGE_ID]: 'Missing the separator argument.'
};

const emptyArraySelector = path => {
const prefix = `${path}.`;
return [
`[${prefix}type="ArrayExpression"]`,
`[${prefix}elements.length=0]`
].join('');
};

const memberExpressionSelector = (path, {property, object}) => {
const prefix = `${path}.`;

const parts = [
`[${prefix}type="MemberExpression"]`,
`[${prefix}computed=false]`,
`[${prefix}optional!=true]`,
`[${prefix}property.type="Identifier"]`,
`[${prefix}property.name="${property}"]`
];

if (object) {
parts.push(
`[${prefix}object.type="Identifier"]`,
`[${prefix}object.name="${object}"]`
);
}

return parts.join('');
};

// `foo.join()`
const arrayJoin = methodSelector({
name: 'join',
length: 0
});

// `[].join.call(foo)` and `Array.prototype.join.call(foo)`
const arrayPrototypeJoin = [
methodSelector({
name: 'call',
length: 1
}),
memberExpressionSelector('callee.object', {property: 'join'}),
`:matches(${
[
emptyArraySelector('callee.object.object'),
memberExpressionSelector('callee.object.object', {property: 'prototype', object: 'Array'})
].join(', ')
})`
].join('');

const selector = `:matches(${arrayJoin}, ${arrayPrototypeJoin})`;

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
return {
[selector](node) {
const [penultimateToken, lastToken] = context.getSourceCode().getLastTokens(node, 2);
const isPrototypeMethod = node.arguments.length === 1;
context.report({
loc: {
start: penultimateToken.loc[isPrototypeMethod ? 'end' : 'start'],
end: lastToken.loc.end
},
messageId: MESSAGE_ID,
/** @param {import('eslint').Rule.RuleFixer} fixer */
fix(fixer) {
let text = '\',\'';

if (isPrototypeMethod) {
text = isCommaToken(penultimateToken) ? `${text},` : `, ${text}`;
}

return fixer.insertTextBefore(lastToken, text);
}
});
}
};
};

const schema = [];

module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Enforce using the separator argument when concatenating elements in an array.',
url: getDocumentationUrl(__filename)
},
fixable: 'code',
schema,
messages
}
};
75 changes: 75 additions & 0 deletions test/array-join-separator.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import outdent from 'outdent';
import {getTester} from './utils/test.mjs';

const {test} = getTester(import.meta);

test.snapshot({
valid: [
'foo.join(",")',
'join()',
'foo.join(...[])',
'foo?.join()',
'foo[join]()',
'foo["join"]()',
'[].join.call(foo, ",")',
'[].join.call()',
'[].join.call(...[foo])',
'[].join?.call(foo)',
'[]?.join.call(foo)',
'[].join[call](foo)',
'[][join].call(foo)',
'[,].join.call(foo)',
'[].join.notCall(foo)',
'[].notJoin.call(foo)',
'Array.prototype.join.call(foo, "")',
'Array.prototype.join.call()',
'Array.prototype.join.call(...[foo])',
'Array.prototype.join?.call(foo)',
'Array.prototype?.join.call(foo)',
'Array?.prototype.join.call(foo)',
'Array.prototype.join[call](foo, "")',
'Array.prototype[join].call(foo)',
'Array[prototype].join.call(foo)',
'Array.prototype.join.notCall(foo)',
'Array.prototype.notJoin.call(foo)',
'Array.notPrototype.join.call(foo)',
'NotArray.prototype.join.call(foo)',
'path.join(__dirname, "./foo.js")'
],
invalid: [
'foo.join()',
'[].join.call(foo)',
'[].join.call(foo,)',
'[].join.call(foo , );',
'Array.prototype.join.call(foo)',
'Array.prototype.join.call(foo, )',
outdent`
(
/**/
[
/**/
]
/**/
.
/**/
join
/**/
.
/**/
call
/**/
(
/**/
(
/**/
foo
/**/
)
/**/
,
/**/
)/**/
)
`
]
});
Loading