Rule proposal: disallow using parseInt by reference
See original GitHub issuePlease describe what the rule should do:
eslint should be able to warn when passing parseInt
by reference instead of directly invoking it, as this likely means a radix is not being passed despite their being a rule to enforce radix usage. Functions like forEach
and map
provide a second argument for the iteration index which, when applied to parseInt
, will be used unintentionally as the radix.
What category of rule is this? (place an “X” next to just one item)
[x] Enforces code style [x] Warns about a potential error [ ] Suggests an alternate way of doing something [ ] Other (please specify:)
Provide 2-3 code examples that this rule will warn about:
// because Array.prototype.map provides a second (index) argument
// this will log `[ 7, NaN ]` where the intent is `[7, 8]`
let arr = ['7', '8']
console.log(arr.map(parseInt))
function mapp(list, fn) {
return list.map(fn)
}
mapper(['0x0101', '100'], parseInt)
Why should this rule be included in ESLint (instead of a plugin)?
It’s high-risk to make this mistake and is not caught by the radix rule despite that partially being intended to avoid issues like this.
Ecmascript functions like Array.prototype.map
, Array.prototype.forEach
, Array.prototype.filter
, and Array.prototype.every
all pass a second index argument to the callback function which can cause usage of parseInt
to mismatch a developer’s expectations.
It’s possible this should instead be enforced when radix
is enabled, or be a configurable option there.
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
On Apr 25, 2017 at 10:50 PM, <Scott Hulbert notifications@github.com> wrote:
@not-an-aardvark https://github.com/not-an-aardvark thanks for the suggestion, here is how I (think) I accomplished this.
Configuration:
{ “rules”: { “no-restricted-syntax”: [ “error”, { “selector”: “CallExpression[mike,mills!=‘parseInt’] > Identifier[name=‘parseInt’]”, “message”: “Call parseInt directly to guarantee radix param is not incorrectly provided” } ] } }
Fails:
‘use strict’ const arr = [‘11’, ‘3’] console.log(arr.map(parseInt))
Passes:
‘use strict’ const arr = [‘11’, ‘3’] console.log(arr.map(function(n) { return parseInt(n) }))
parseInt(5, 10) // not really safe but eslint doesn’t support catching this AFAIKlet fun = parseIntconsole.log(arr.map(fun))
— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/eslint/eslint/issues/8214#issuecomment-297222523, or mute the thread https://github.com/notifications/unsubscribe-auth/AYEjEogqmNy8ycykBOLwIW76W4hsSiu9ks5rzrD9gaJpZM4MWfjj .
@not-an-aardvark thanks for the suggestion, here is how I (think) I accomplished this.
Configuration:
Fails:
Passes: