I was writing a function that takes an argument and returns a truth value.
My initial idea was just return !!value
, but this will fail for '0'
, {}
or []
. I know that '0'
should be true but in my application we are considering it false.
So, my function should return false for:
- Falsey values:
false
,0
,undefined
,null
,''
- Blank values:
{}
,[]
- Special requirement:
'0'
So considering it, I updated code to following to handle
var isTrue = function(value) {
switch (typeof(value)) {
case "string":
return !(value === '0' || value === 'false');
case "number":
case "boolean":
return !!value;
case "object":
return Object.keys(value).length > 0
}
}
console.log(false,isTrue(false))
console.log(true,isTrue(true))
console.log(0,isTrue(0))
console.log(1,isTrue(1))
console.log('0',isTrue('0'))
console.log('1',isTrue('1'))
console.log('test',isTrue('test'))
console.log('Object',isTrue({}))
console.log('Array',isTrue([]))
Now this works fine. It does not include handling for functions
but that is out of scope of current question. My question is, is there a better way to handle the same?
0
as false and1
as true. But some apps depend on localStorage, so sometimes we get'0'
or'1'
. I also thought to extend its scope as it a generic function, so added functionality forboolean
and boolean as string('true', 'false') andobject/arrays
\$\endgroup\$isMySpecialPropertyTrue
(with "MySpecialProperty" of course a phrase referring to the context you are using it in). \$\endgroup\$