Skip to content

Latest commit

 

History

History
182 lines (134 loc) · 3.15 KB

no-array-callback-reference.md

File metadata and controls

182 lines (134 loc) · 3.15 KB

Prevent passing a function reference directly to iterator methods

💼 This rule is enabled in the ✅ recommended config.

💡 This rule is manually fixable by editor suggestions.

Passing functions to iterator methods can cause issues when the function is changed without realizing that the iterator passes 2 more parameters to it. This also applies when using TypeScript, albeit only if the function accepts the same parameter type used by the iterator method.

Suppose you have a unicorn module:

module.exports = x => x + 1;

You can then use it like this:

const unicorn = require('unicorn');

[1, 2, 3].map(unicorn);
//=> [2, 3, 4]

The unicorn module now does a minor version that adds another argument:

module.exports = (x, y) => x + (y ? y : 1);

Your code will now return something different and probably break for users because it is now passing the index of the item as second argument.

const unicorn = require('unicorn');

[1, 2, 3].map(unicorn);
//=> [2, 3, 5]

This rule helps safely call the function with the expected number of parameters:

const unicorn = require('unicorn');

[1, 2, 3].map(x => unicorn(x));
//=> [2, 3, 4]

Fail

const foo = array.map(callback);
array.forEach(callback);
const foo = array.every(callback);
const foo = array.filter(callback);
const foo = array.find(callback);
const index = array.findIndex(callback);
const foo = array.some(callback);
const foo = array.reduce(callback, 0);
const foo = array.reduceRight(callback, []);
const foo = array.flatMap(callback);
array.forEach(someFunction({foo: 'bar'}));
array.forEach(callback, thisArgument);

Pass

const foo = array.map(element => callback(element));
const foo = array.map(Boolean);
array.forEach(element => {
	callback(element);
});
const foo = array.every(element => callback(element));
const foo = array.filter(element => callback(element));
const foo = array.filter(Boolean);
const foo = array.find(element => callback(element));
const index = array.findIndex(element => callback(element));
const foo = array.some(element => callback(element));
const foo = array.reduce(
	(accumulator, element) => accumulator + callback(element),
	0
);
const foo = array.reduceRight(
	(accumulator, element) => [
		...accumulator,
		callback(element)
	],
	[]
);
const foo = array.flatMap(element => callback(element));
const callback = someFunction({foo: 'bar'});

array.forEach(element => {
	callback(element);
});
array.forEach(function (element) {
	callback(element, this);
}, thisArgument);
function readFile(filename) {
	return fs.readFile(filename, 'utf8');
}

Promise.map(filenames, readFile);