vendredi 27 janvier 2017

How to avoid a lot of conditional programmin javascript

I want to ask some ninjas of javascript about conditional (if\else) statements.

Let's imagine that we have this code:

There is a lot of standard data-checking (if property exists... for..if has own...end etc.) So does it a "normal code"? Because my Java friend saw it and he asked me: Why do you wrote a low-quality code bro?

And other question: Is there some way exists to simplify data-checking in every method etc? For ex: "check if property in obj exists". (I didn't want to use typescript). I worked with it a lot but I want to know how it can be done by the plain JS. (I tried to use es7 decorators but they are only working with methods. Not the pure function etc.)

Thanks for any help!

var resultList;
var obj = {

    elem1 : [
    {
        "type" : "zeta_0"
    },
    {
        "type" : "beta_0"
    },
    {
        "type" : "omega_0"
    }
  ],

    elem2 : [
    {
        "type" : "zeta_1"
    },
    {
        "type" : "beta_1"
    },
    {
        "type" : "omega_1"
    }
  ]

}

function fillResultSet(sourceData) {

    var res = [];

    if (sourceData && sourceData.elem1) {

    for (var key in sourceData) {

      if (sourceData.hasOwnProperty(key)) {
        res.push(sourceData[key][0].type);
      }

    }

  }

  return res;

}

resultList = fillResultSet(obj);

Demo

Aucun commentaire:

Enregistrer un commentaire