1

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?

Roni Gadot
  • 437
  • 2
  • 19
  • 30
  • You're going to have to check your configuration object at some point with an `if` ... – Zenoo Feb 08 '18 at 10:04
  • Write a helper function that does it for you. – connexo Feb 08 '18 at 10:05
  • Possible duplicate of [javascript test for existence of nested object key](https://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – connexo Feb 08 '18 at 10:06

1 Answers1

0

you could create a function mapping object like so:

const mapping = {
  "name":()=>{
    //process the data according to name configuration
  },
  "dimension_name":()=>{
    //process the data according to name and dimension configuration
  }
};

then on your code you can build the appropriate key by filtering properties not related to your logic like so:

const properties = ["dimension","name"];
const selectedProcess = Object.keys(confObject).filter((key) => {
  return properties.indexOf(key) !== -1;
}).sort().join("_");

that will return "name" when only name property was present on the config, and dimension_name when both properties exists.

Then you can just call the right method according to that key, like so:

mapping[selectedProcess]();

you can add as many properties as you like, just remember to update the properties array.

Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186