Reputation: 5198
I want to make a function warn
that serves as a light general error handling function which does the following:
NaN
, null
, undefined
, but could be []
, ''
,etc)Currently, this is what I have:
function warn(thing, thingString, shouldNotBe, fatal, verbose){
// default verbose
if (verbose == undefined) {verbose = true;}
// default fatal
if (verbose == undefined) {verbose = false;}
if (
thing == shouldNotBe || // test for undefined and null
(isNaN(shouldNotBe) && shouldNotBe != undefined && isNaN(thing)) // test for NaN
) {
message = thingString + ' is ' + shouldNotBe
if (fatal) { message = '[FATAL]: ' + message}
if ( verbose ) { console.warn( message ) }
if ( fatal ) { return true }
else { return false }
}
}
This lets me do the following in my code:
var myVar
fatal = warn(myVar, 'myVar', undefined, true)
if ( fatal ) {return}
> [Fatal]: myVar is undefined
The problem I am facing is JS's NaN:
NaN === NaN ---> (false)
NaN == NaN ---> (false)
isNaN(NaN) ---> (true)
isNaN(undefined) ---> (true)
isNaN(null) ---> (false)
So I have to have this ugly conditional (which I could shorten):
(isNaN(shouldNotBe) && shouldNotBe != undefined && isNaN(thing))
to:
shouldNotBe
is not a number (undefined
or NaN
)shouldNotBe
is not undefinedthing
is also NaN
So my question is there a better way to approach this problem? The fact that NaN
can not be tested by conditional really throws a wrench in this.
Upvotes: 0
Views: 50
Reputation: 665276
You can shorten the part isNaN(shouldNotBe) && shouldNotBe != undefined
to Number.isNaN(shouldNotBe)
. You might also be able to use Object.is
instead of ==
, but then you need special cases for null == undefined
and +0 == -0
.
Upvotes: 1