From 7051fe6657bbcd526018e44d0e2e3a2bd28fa700 Mon Sep 17 00:00:00 2001 From: francesco Date: Mon, 18 Mar 2024 17:28:32 +0100 Subject: [PATCH] perf: reduce if statement for `NaN` (micro-optimization) (#697) * chore(perf): reduce if statement for `NaN` Signed-off-by: francesco * isInteger return false for Infinity and NaN Signed-off-by: francesco * fast check for NaN Signed-off-by: francesco * disable lint Signed-off-by: francesco * disable only for self-compare NaN Co-authored-by: Aras Abbasi Signed-off-by: francesco * fast check for NaN Signed-off-by: francesco --------- Signed-off-by: francesco Co-authored-by: Aras Abbasi --- lib/serializer.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/serializer.js b/lib/serializer.js index 9a3bbd4e..1ad588a1 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -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) @@ -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'