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?