Is there a method to reduce conditions?

Viewed 50

Is it possible to reduce all the conditions to one single condition?

Long code for example:

  let one = 'one'
  let two = 'two'
  let three = 'three'
  let four = 'four'
  if(one = 'one'){
    if(two = 'two'){
      if(three = 'three'){
        if(four = 'four'){

        }
      }
    }
  }

Can it be just one line?

3 Answers

Two changes must be made so

let one = 'one'
let two = 'two'
let three = 'three'
let four = 'four'
if(one === 'one' && two === 'two' && three === 'three' && four === 'four'){

}

The first change is adding && The second change is replacing = with ===

I'd approach it by extracting the checks into a function to keep it readable:


function checkMyInput(one, two, three) {
  if (one !== 'one') return false;
  if (two !== 'two') return false;
  if (three !== 'three') return false;

  return true;
}

if (checkMyInput('one', 'two', 'three')) {
  // the code you want to run
}

I wouldn't necessarily try to concatenate them in a single line. In programming you don't get extra points for making something concise, you usually get extra points for making something readable. Returning early is an option to make the reasoning about why something resolves to true or false easier to understand.

And the checkMyInput function can be extracted somewhere else, so you don't have to keep looking at it.

Depending on how many variables you're doing this for it might be easier to use an object to hold key/value pairs, and then write a helper function that iterates over the Object.entries using every to check that each key and value are the same.

const obj = {
  one: 'one',
  two: 'two',
  three: 'three',
  four: 'four'
};

function keyValueSame(obj) {
  return Object.entries(obj).every(([ key, value ]) => {
    return key === value;
  });
}

console.log(keyValueSame(obj));

Related