jeudi 8 février 2018

JS - How to avoid long if else statement when condition is based on Object's property availability

Given a configuration object my function should do one of several data processing.

For example, giving the following config:

{
  name:"my data"
}

the processed results would be:

[{
   name:"my data",
   data:[1,2,3,4,5,6,7,8]
}]

If the config is:

{
   name:"my data",
   dimension: "group_name"
}

Then the results, is grouped by the dimension and the output is:

[
 {
   name:"group 1",
   data:[0.5,0.5]
 },
 {
   name:"group 2",
   data:[1,1]
 },
 {
   name:"group 3",
   data:[2,2]
 }
// And so on ...
]

There are several configurations available, and I want to avoid a long if else / switch case statement that checks the existence of the required object properties.

What is a more elegant alternative?

Aucun commentaire:

Enregistrer un commentaire