Skip to content

Commit

Permalink
prefer-spread: Ignore {arrayBuffer,blob,buffer,file,this}.slice() (
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed May 18, 2021
1 parent f14a9d1 commit e18d5f2
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 6 deletions.
2 changes: 2 additions & 0 deletions docs/rules/prefer-spread.md
Expand Up @@ -16,6 +16,8 @@ Enforces the use of [the spread operator (`...`)](https://developer.mozilla.org/

Shallow copy an `Array`.

Variables named `arrayBuffer`, `blob`, `buffer`, `file`, and `this` are ignored.

This rule is partly fixable.

## Fail
Expand Down
8 changes: 3 additions & 5 deletions rules/no-array-callback-reference.js
Expand Up @@ -78,7 +78,8 @@ const ignoredCallee = [
'underscore',
'_',
'Async',
'async'
'async',
'this'
];

function check(context, node, method, options) {
Expand Down Expand Up @@ -155,10 +156,7 @@ const create = context => {
].join('');

rules[selector] = node => {
if (
isNodeMatches(node.callee.object, ignoredCallee) ||
node.callee.object.type === 'ThisExpression'
) {
if (isNodeMatches(node.callee.object, ignoredCallee)) {
return;
}

Expand Down
13 changes: 13 additions & 0 deletions rules/prefer-spread.js
Expand Up @@ -8,6 +8,7 @@ const shouldAddParenthesesToSpreadElementArgument = require('./utils/should-add-
const replaceNodeOrTokenAndSpacesBefore = require('./utils/replace-node-or-token-and-spaces-before');
const removeSpacesAfter = require('./utils/remove-spaces-after');
const isLiteralValue = require('./utils/is-literal-value');
const {isNodeMatches} = require('./utils/is-node-matches');

const ERROR_ARRAY_FROM = 'array-from';
const ERROR_ARRAY_CONCAT = 'array-concat';
Expand Down Expand Up @@ -62,6 +63,14 @@ const arraySliceCallSelector = [
'[callee.object.type!="ArrayExpression"]'
].join('');

const ignoredSliceCallee = [
'arrayBuffer',
'blob',
'buffer',
'file',
'this'
];

const isArrayLiteral = node => node.type === 'ArrayExpression';
const isArrayLiteralHasTrailingComma = (node, sourceCode) => {
if (node.elements.length === 0) {
Expand Down Expand Up @@ -392,6 +401,10 @@ const create = context => {
context.report(problem);
},
[arraySliceCallSelector](node) {
if (isNodeMatches(node.callee.object, ignoredSliceCallee)) {
return;
}

const [firstArgument] = node.arguments;
if (firstArgument && !isLiteralValue(firstArgument, 0)) {
return;
Expand Down
8 changes: 7 additions & 1 deletion test/prefer-spread.mjs
Expand Up @@ -288,7 +288,13 @@ test.snapshot({
'array.notSlice()',
// Why would someone write these
'[...foo].slice()',
'[foo].slice()'
'[foo].slice()',
// Ignored
'arrayBuffer.slice()',
'blob.slice()',
'buffer.slice()',
'file.slice()',
'class A {foo() {this.slice()}}'
],
invalid: [
'array.slice()',
Expand Down

0 comments on commit e18d5f2

Please sign in to comment.