How to write multiple if judgments gracefully

Posted by Daniel0 on Sun, 23 Feb 2020 11:01:48 +0100

Preface
In daily projects, we often use if to judge, but in multi-level projects, you will find that the code is cumbersome
demand
Now there are four products, namely mobile phones, computers, televisions and game consoles. Of course, the prices of each product are different
if judgement
To see such a requirement, write an if judgment as soon as possible. It's simple and fast. Let's take a look at the code

let commodity = {
  phone: 'Mobile phone',
  computer: 'Computer',
  television: 'television',
  gameBoy: 'Recreational machines'
}

if (commodity.phone) {
  // do someThing
} else if (commodity.computer) {
  // do someThing
} else if (commodity.television) {
  // do someThing
} else if (commodity.gameBoy) {
  // do someThing
}

This way, it can also be realized, but once there are multiple judgments, the code is too long, and maintenance and reading are not friendly
Switch
At this time, we consider using Switch

let commodity = {
  phone: 'Mobile phone',
  computer: 'Computer',
  television: 'television',
  gameBoy: 'Recreational machines'
}
const price = (name) => {
  switch (name) {
    case commodity.phone: 
      console.log(9999)
      break
    case commodity.computer: 
      console.log(15999)
      break
    case commodity.television: 
      console.log(1999)
      break
    case commodity.gameBoy: 
      console.log(2500)
      break
  }
}
price('Mobile phone') // 9999

But from this point of view, it seems that we can't solve the problem fundamentally, but the code is a little simpler
Map
What is Map?
Create Map object

const commodity = new Map([
  ['phone', 9999],
  ['computer', 15999],
  ['television', 2999],
  ['gameBoy', 2599]
])

Create get price function

const price = (name) => {
  return commodity.get(name)
}
price('phone') // 9999

This is much simpler than if and switch code and greatly improves the readability
To achieve this, suddenly the product manager said, now the new year's day, the goods have to be preferential, you need to set different prices in different time periods, and the logic will be different, you can't call the same function, at this time, many if judgments are born again, what double 11 double 12 Year Festival
If you write by if, you will nest if in if again. This code can be imagined
Key usage object in Map
At this time, Map has solved this problem for us

const commodity = new Map([
  [{name: 'phone', date: '11-11'}, () => {
    console.log(9999)
    // do Something
  }],
  [{name: 'phone', date: '12-12'}, () => {
    console.log(9888)
    // do Something
  }],
  [{name: 'phone', date: '06-18'}, () => {
    console.log(9799)
    // do Something
  }],
  [{name: 'phone', date: '09-09'}, () => {
    console.log(9699)
    // do Something
  }],
]);
const showPrice = (name, date) => {
  [...commodity].forEach(([key,value])=> {
    key.name === name && key.date === date ? value.call() : ''
  })
}
showPrice('phone', '12-12')

In this way, the code is easier to read, neat and beautiful
What if there is the same logic for a certain period of time?
We can consider caching the same logic

const CheckPrice = () => {
  const showMessage = () => {
    console.log('Open activity page')
  }
  return new Map ([
    [{name: 'phone', date: '11-11'}, () => {
      console.log(9999)
      showMessage()
      // do Something
    }],
    [{name: 'phone', date: '12-12'}, showMessage],
    [{name: 'phone', date: '06-18'}, () => {
      console.log(9799)
      // do Something
    }],
    [{name: 'phone', date: '09-09'}, () => {
      console.log(9699)
      // do Something
    }],
  ])
}
const showPrice = (name, date) => {
  [...CheckPrice()].forEach(([key,value])=> {
    key.name === name && key.date === date ? value.call() : ''
  })
}
showPrice('phone', '11-11')

Can it be simplified again?
Optimization by regularization

const CheckPrice = () => {
  const showMessage = () => {
    console.log('Open activity page')
  }
  return new Map ([
   [/^phone_[0-4]$/, () => {
     console.log('The price of event time is 8888')
   }],
   [/^phone_[5-9]*$/, () => {
     console.log('Other time 10000')
   }],
   [/^phone_.*$/, () => {
    showMessage()
   }],
  ])
}
const showPrice = (name, date) => {
  [...CheckPrice()].forEach(([key,value])=> {
    key.test(`${name}_${date}`) ? value.call() : ''
  })
}
let date = [{date: '11-11', key: 1}, {date: '12-28', key: 9}]
let target = date.find((item, index) => item.date === '12-28')
showPrice('phone', target.key)
Published 15 original articles, won praise 6, visited 5808
Private letter follow

Topics: Mobile