eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Contradictory rules intent

Open user72356 opened this issue 3 years ago • 1 comments

Aren't no-array-callback-reference and prefer-native-coercion-functions contradictory in their intent? Consider the following:

const idsAsNumber = idsAsString.map(id => Number(id));

According to prefer-native-coercion-functions I should do:

const idsAsNumber = idsAsString.map(Number);

It goes against the spirit of no-array-callback-reference.

"What if" the Number constructor changed? I know it's unlikely because it's core JS but it still seems inconsistent when we're applying those what-ifs to pretty much anything else.

user72356 avatar Jul 10 '22 16:07 user72356

"What if" the Number constructor changed?

It's never going to happen.

The number one guiding principle, which the committee is unbending on, is “Don’t Break the Web”.

fisker avatar Jul 10 '22 17:07 fisker

@fisker Initial question did not get anwser :

What should we do if we cannot use :

  • const idsAsNumber = idsAsString.map(Number); ==> no-array-callback-reference rule
  • neither const idsAsNumber = idsAsString.map(id => Number(id)); ==> prefer-native-coercion-functions rule

but still need to do this mapping anyway ?

IMO, the two rules are in conflict ... at least concerning Number()

msieurtoph avatar Sep 04 '23 08:09 msieurtoph

Use idsAsString.map(Number);, it's allowed in no-array-callback-reference.

fisker avatar Sep 04 '23 11:09 fisker

@fisker Sorry, I was not clear enough : Imagine you need to filter (not map) on number element, like in the following case :

[null, 'string', 1, 2, '3', 4, 'foo', 'bar' ].filter(Number).forEach(console.log)
// will only console.log : 
// 1
// 2
// '3'
// 4

I do not want to map, I want to filter and keep only number-like element ( and !=0) before running the rest of the chain with their original values.

msieurtoph avatar Sep 04 '23 20:09 msieurtoph

It's common to filter with .filter(Boolean), if you want filter out "0" too, you may want try .filter(element => Number(element) !== 0), it's more clear.

fisker avatar Sep 05 '23 00:09 fisker

Excluding 0 was unintended, it was a bug. I guess I will finally go with a .filter(_element => !Number.isNaN(Number(_element))). Thx for interesting reflection.

msieurtoph avatar Sep 05 '23 07:09 msieurtoph