Skip to content

Latest commit

 

History

History
173 lines (114 loc) · 2.12 KB

no-fn-reference-in-iterator.md

File metadata and controls

173 lines (114 loc) · 2.12 KB

Prevents passing a function reference directly to iterator methods

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 fn = x => x + 1;

[1, 2, 3].map(fn);
const fn = x => console.log(x);

[1, 2, 3].forEach(fn);
const fn = x => x < 10;

[1, 2, 3].every(fn);
const fn = x => x % 2;

[1, 2, 3].filter(fn);
const fn = x => x === 1;

[1, 2, 3].find(fn);
const fn = x => x === 1;

[1, 2, 3].findIndex(fn);
const fn = x => x === 2;

[1, 2, 3].some(fn);
const fn = (a, b) => a + b;

[1, 2, 3].reduce(fn, 0);
const fn = (a, b) => a.concat(b);

[1, 2, 3].reduceRight(fn, []);
const fn = x => x === 2;

[1, 2, 3].map(m({foo: 'bar'}));

Pass

const fn = x => x + 1;

[1, 2, 3].map(x => fn(x));
const fn = x => console.log(x);

[1, 2, 3].forEach(x => fn(x));
const fn = x => x < 10;

[1, 2, 3].every(x => fn(x));
const fn = x => x % 2;

[1, 2, 3].filter(x => fn(x));
[undefined, 2, 3].filter(Boolean);
const fn = x => x === 1;

[1, 2, 3].find(x => fn(x));
const fn = x => x === 1;

[1, 2, 3].findIndex(x => fn(x));
const fn = x => x === 2;

[1, 2, 3].some(x => fn(x));
const fn = (a, b) => a + b;

[1, 2, 3].reduce((a, b) => fn(a, b), 0);
const fn = (a, b) => a.concat(b);

[1, 2, 3].reduceRight((a, b) => fn(a, b), []);
const fn = (a, b) => a.concat(b);

[1, 2, 3].reduceRight(fn, []);
const fn = x => x === 2;

[1, 2, 3].map(x => m({foo: 'bar'})(x));
const fn = x => x === 2;

Promise.map(filenames, fn);