How to refactor excess of conditions if?

2

I have the following block of code:

data.split('\n').map(l => {
    if (/^videoW/.exec(l)) {
      vidConf.videoW = l.split('=')[1]
    }
    if (/^videoH/.exec(l)) {
      vidConf.videoH = l.split('=')[1]
    }
    if (/^videoT/.exec(l)) {
      vidConf.videoT = l.split('=')[1]
    }
    if (/^videoL/.exec(l)) {
      vidConf.videoL = l.split('=')[1]
    }
    if (/^time=/.exec(l)) {
      vidConf.timeImg = l.split('=')[1]
    }
    if (/^auto=/.exec(l)) {
      vidConf.videoA = l.split('=')[1]
    }
    if (/^typeP=/.exec(l)) {
      vidConf.typeP = l.split('=')[1]
    }

  })

To the data array I cut it by the line breaks ( \n ), because I extract it from an external file and perform a map on it to check the existence of some variables in the using regular expressions and in this way pass the data to the variable vidConf .

How could I refactor this code avoiding so many sentences if , and achieving the same result?

    
asked by Travv 21.12.2017 в 20:13
source

1 answer

3

You could create a arrangement with the list of "cases" ( eg: ifs ) and then for each line evaluate them one by one.

We can use some to avoid controlling all the cases.

  

some() executes the function callback once for each element present in the array until it finds one where callback returns a true value (true). If that element is found, some() returns true immediately.

Example:

let data = 'videoWeight=18
videoHeight=20
time=200
auto=true';
let vidConf = {};
let vidProps = [
  {re: /^videoW/, name: 'videoW'},
  {re: /^videoH/, name: 'videoH'},
  {re: /^videoT/, name: 'videoT'},
  {re: /^videoL/, name: 'videoL'},
  {re: /^time$/, name: 'timeImg'},
  {re: /^auto$/, name: 'videoA'},
  {re: /^typeP$/, name: 'typeP'}
]

data.split('\n').map(l => {
  let info = l.split('=');
  let name = info[0];
  let value = info[1];
  
  vidProps.some(prop => {
    if (prop.re.exec(name)) {
      vidConf[prop.name] = value;
      return true;
    }
    return false;
  });
})

console.log(vidConf);
    
answered by 21.12.2017 / 20:32
source