3
\$\begingroup\$

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 Arrays, but that's all I can think of offhand. Any other ideas on making this more general?

\$\endgroup\$

1 Answer 1

11
\$\begingroup\$

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.

\$\endgroup\$
1
  • 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\$ Commented Oct 5, 2015 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.