patternjavascriptModerate
Check if JavaScript input is empty
Viewed 0 times
javascriptinputcheckempty
Problem
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
Basic [SONA!] testing
I'm tempted to modify the object line to check if the
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 Arrays, but that's all I can think of offhand. Any other ideas on making this more general?Solution
One edge case you're missing is how to handle
Also be aware that
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.Context
StackExchange Code Review Q#106591, answer score: 11
Revisions (0)
No revisions yet.