Skip to content

Commit

Permalink
add tests and comment for prefer-numeric-literals
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic committed Aug 18, 2020
1 parent 1d6eee5 commit 371e46a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/rules/prefer-numeric-literals.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,16 @@ module.exports = {
/*
* If the newly-produced literal would be invalid, (e.g. 0b1234),
* or it would yield an incorrect parseInt result for some other reason, don't make a fix.
*
* If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+`
* per the specification doesn't support numeric separators. Thus, the above condition will be `true`
* (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value.
* Consequently, no autofixes will be made. This is correct behavior because `parseInt` also
* doesn't support numeric separators, but it does parse part of the string before the first `_`,
* so the autofix would be invalid:
*
* parseInt("1_1", 2) // === 1
* 0b1_1 // === 3
*/
return null;
}
Expand Down
26 changes: 25 additions & 1 deletion tests/lib/rules/prefer-numeric-literals.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const rule = require("../../../lib/rules/prefer-numeric-literals"),
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2020 } });
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2021 } });

ruleTester.run("prefer-numeric-literals", rule, {
valid: [
Expand Down Expand Up @@ -345,6 +345,30 @@ ruleTester.run("prefer-numeric-literals", rule, {
code: "(Number?.parseInt)?.(\"1F7\", 16) === 255;",
output: "0x1F7 === 255;",
errors: [{ message: "Use hexadecimal literals instead of Number?.parseInt()." }]
},

// `parseInt` doesn't support numeric separators. The rule shouldn't autofix in those cases.
{
code: "parseInt('1_0', 2);",
output: null,
errors: [{ message: "Use binary literals instead of parseInt()." }]
},
{
code: "Number.parseInt('5_000', 8);",
output: null,
errors: [{ message: "Use octal literals instead of Number.parseInt()." }]
},
{
code: "parseInt('0_1', 16);",
output: null,
errors: [{ message: "Use hexadecimal literals instead of parseInt()." }]
},
{

// this would be indeed the same as `0x0_0`, but there's no need to autofix this edge case that looks more like a mistake.
code: "Number.parseInt('0_0', 16);",
output: null,
errors: [{ message: "Use hexadecimal literals instead of Number.parseInt()." }]
}
]
});

0 comments on commit 371e46a

Please sign in to comment.