Skip to content

Commit

Permalink
Update: improve use-isnan rule to detect Number.NaN (fixes #14715) (#…
Browse files Browse the repository at this point in the history
…14718)

* Update: improve `isNaNIdentifier` to detect `Number.isNaN` (fixes #14715)

* Chore: add test cases for `Number.NaN`

* Docs: add more examples for `use-isnan`

* Chore: improve logic and add more test cases

* Docs: Update docs/rules/use-isnan.md

Co-authored-by: Milos Djermanovic <[email protected]>

Co-authored-by: Milos Djermanovic <[email protected]>
  • Loading branch information
snitin315 and mdjermanovic authored Jun 26, 2021
1 parent b08170b commit 104c0b5
Show file tree
Hide file tree
Showing 3 changed files with 396 additions and 1 deletion.
48 changes: 48 additions & 0 deletions docs/rules/use-isnan.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ if (foo == NaN) {
if (foo != NaN) {
// ...
}

if (foo == Number.NaN) {
// ...
}

if (foo != Number.NaN) {
// ...
}
```

Examples of **correct** code for this rule:
Expand Down Expand Up @@ -77,6 +85,26 @@ switch (NaN) {
break;
// ...
}

switch (foo) {
case Number.NaN:
bar();
break;
case 1:
baz();
break;
// ...
}

switch (Number.NaN) {
case a:
bar();
break;
case b:
baz();
break;
// ...
}
```

Examples of **correct** code for this rule with `"enforceForSwitchCase"` option set to `true` (default):
Expand Down Expand Up @@ -126,6 +154,26 @@ switch (NaN) {
break;
// ...
}

switch (foo) {
case Number.NaN:
bar();
break;
case 1:
baz();
break;
// ...
}

switch (Number.NaN) {
case a:
bar();
break;
case b:
baz();
break;
// ...
}
```

### enforceForIndexOf
Expand Down
5 changes: 4 additions & 1 deletion lib/rules/use-isnan.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ const astUtils = require("./utils/ast-utils");
* @returns {boolean} `true` if the node is 'NaN' identifier.
*/
function isNaNIdentifier(node) {
return Boolean(node) && node.type === "Identifier" && node.name === "NaN";
return Boolean(node) && (
astUtils.isSpecificId(node, "NaN") ||
astUtils.isSpecificMemberAccess(node, "Number", "NaN")
);
}

//------------------------------------------------------------------------------
Expand Down
Loading

0 comments on commit 104c0b5

Please sign in to comment.