Skip to content

Commit

Permalink
perf: reduce if statement for NaN (micro-optimization) (#697)
Browse files Browse the repository at this point in the history
* chore(perf): reduce if statement for `NaN`

Signed-off-by: francesco <[email protected]>

* isInteger return false for Infinity and NaN

Signed-off-by: francesco <[email protected]>

* fast check for NaN

Signed-off-by: francesco <[email protected]>

* disable lint

Signed-off-by: francesco <[email protected]>

* disable only for self-compare NaN

Co-authored-by: Aras Abbasi <[email protected]>
Signed-off-by: francesco <[email protected]>

* fast check for NaN

Signed-off-by: francesco <[email protected]>

---------

Signed-off-by: francesco <[email protected]>
Co-authored-by: Aras Abbasi <[email protected]>
  • Loading branch information
cesco69 and Uzlopak authored Mar 18, 2024
1 parent b07e607 commit 7051fe6
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ module.exports = class Serializer {

asInteger (i) {
if (typeof i === 'number') {
if (i === Infinity || i === -Infinity) {
throw new Error(`The value "${i}" cannot be converted to an integer.`)
}
if (Number.isInteger(i)) {
return '' + i
}
if (Number.isNaN(i)) {
// check if number is Infinity or NaN
// eslint-disable-next-line no-self-compare
if (i === Infinity || i === -Infinity || i !== i) {
throw new Error(`The value "${i}" cannot be converted to an integer.`)
}
return this.parseInteger(i)
Expand All @@ -52,7 +51,9 @@ module.exports = class Serializer {

asNumber (i) {
const num = Number(i)
if (Number.isNaN(num)) {
// check if number is NaN
// eslint-disable-next-line no-self-compare
if (num !== num) {
throw new Error(`The value "${i}" cannot be converted to a number.`)
} else if (!Number.isFinite(num)) {
return 'null'
Expand Down

0 comments on commit 7051fe6

Please sign in to comment.