Having a general utility function to see if the input is empty makes sense to me. Empty means different things depends on the type. I just spent ~5 minutes writing this one up, so I'm sure it's missing edge cases, and maybe I'm approaching the whole problem incorrectly.
Function
function isEmpty(input: any) {
switch (typeof input) {
case 'string':
return input.length === 0;
case 'object':
return (input instanceof Array)? input.length === 0: Object.getOwnPropertyNames(input).length === 0;
case 'number':
default:
return input === undefined;
}
}
Basic [SONA!] testing
let s = '';
let o = {};
let n: number;
let a = [];
console.log('isEmpty(s): ' + isEmpty(s));
console.log('isEmpty(o): ' + isEmpty(o));
console.log('isEmpty(n): ' + isEmpty(n));
console.log('isEmpty(a): ' + isEmpty(a));
I'm tempted to modify the object line to check if the length
property is defined, rather than restricting to Array
s, but that's all I can think of offhand. Any other ideas on making this more general?
1 Answer 1
One edge case you're missing is how to handle null
. isEmpty(null)
will fail because Object.getOwnPropertyNames(null)
will throw TypeError: can't convert null to object
.
Also be aware that isEmpty(NaN)
will return false
, which may or may not be what you want.
-
1\$\begingroup\$ Welcome to Code Review! Don't worry, this is a valid review! Even if your review is short or only points out flaws rather than solutions it is valuable to the OP and can be posted as an answer. \$\endgroup\$SuperBiasedMan– SuperBiasedMan2015年10月05日 10:33:53 +00:00Commented Oct 5, 2015 at 10:33
Explore related questions
See similar questions with these tags.