Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Having a general utility function to see if the input is empty makes sense to me. Empty means different things depends on the type. 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 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?

share|improve this question

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.

share|improve this answer
1  
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. –  SuperBiasedMan 23 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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