mercredi 27 juin 2018

How to simplify this test if variable is "something"?

In node I want to test whether the variable i give to a function is "something". With that I mean not a null value or an empy array or empty object. So I wrote the following, which works as expected:

function f(v) {
    if (v === null) {
        return false;
    }
    if (v.constructor === Array) {
        if (v.length) {
            return true;
        } else {
            return false;
        }
    }
    if (v.constructor === Object) {
        if (Object.keys(v).length) {
            return true;
        } else {
            return false;
        }
    }
}

f(null);  // false
f([]);  // false
f({}); // false
f([1]); // true
f({a: 1}); // true

This just seems horribly verbose. I presume there's an easier/simpler way of doing this. This is an option, but less readable and I think still too verbose:

function f(v) {
    if (v === null) {
        return false;
    }
    if (v.constructor === Array) {
        return !!v.length;
    }
    if (v.constructor === Object) {
        return !!Object.keys(v).length;
    }
}

I would expect it to be possible to reduce this to a one liner. Any idea how I would be able to do that?

Aucun commentaire:

Enregistrer un commentaire