mercredi 6 mai 2020

Refactor If else logic [closed]

I currently have the following code. I am using if statements to set the state in react code.I was hving multiple and and OR condition in the if statement should i take out all the common condition into a single boolean value and add it to the repeating code

    if (
  this.state.device.user_state == 2 &&
  this.state.device.manually_terminated == false &&
  (!this.state.device.hasOwnProperty("files") ||
    !this.state.device.files.hasOwnProperty("bin180") ||
    (this.state.device.files.hasOwnProperty("bin180") &&
      !(this.state.device.files.bin180[0].file0[0] == "Full Data")))
) {
  var file = this.state.fileOption;

  file.push({ value: 2, label: constants.BINARY180 });

  this.setState({
    fileOption: file,
    showGenerateFile: true,
  });
}
if (
  this.state.device.user_state == 2 &&
  this.state.device.manually_terminated == false &&
  (!this.state.device.hasOwnProperty("files") ||
    !this.state.device.files.hasOwnProperty("bin244") ||
    (this.state.device.files.hasOwnProperty("bin244") &&
      !(this.state.device.files.bin244[0].file0[0] == "Full Data")))
) {
  var file = this.state.fileOption;

  file.push({ value: 3, label: constants.BINARY244 });

  this.setState({
    fileOption: file,
    showGenerateFile: true,
  });
}
if (
  this.state.device.user_state == 2 &&
  this.state.device.manually_terminated == false &&
  (!this.state.device.hasOwnProperty("files") ||
    !this.state.device.files.hasOwnProperty("edf") ||
    (this.state.device.files.hasOwnProperty("edf") &&
      !(this.state.device.files.edf[0].file0[0] == "Full Data")))
) {
  var file = this.state.fileOption;
  file.push({ value: 1, label: constants.EDF });

  this.setState({
    fileOption: file,
    showGenerateFile: true,
  });
}
if (
  this.state.device.user_state == 2 &&
  this.state.device.manually_terminated == false &&
  (!this.state.device.hasOwnProperty("files") ||
    !this.state.device.files.hasOwnProperty("mit_bih") ||
    (this.state.device.files.hasOwnProperty("mit_bih") &&
      !(this.state.device.files.mit_bih[0].file0[0] == "Full Data")))
) {
  var file = this.state.fileOption;

  file.push({ value: 4, label: constants.MIT_BIH });
  this.setState({
    fileOption: file,
    showGenerateFile: true,
  });
}

How should I refactor this into something more managable?

Aucun commentaire:

Enregistrer un commentaire