Skip to content

Latest commit

 

History

History
171 lines (127 loc) · 2.7 KB

no-array-callback-reference.md

File metadata and controls

171 lines (127 loc) · 2.7 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.

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]

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);