By Damian Ciplat

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

While refactoring code recently, I found that earlier code used too many if statements to a degree I’d never seen before. That’s why I think it’s important to share these simple tips to help us avoid overusing if statements.

Here are six ways to replace the use of if, not by rejecting if paranoia, but by rethinking how we code.

1. Ternary operators

Case 1

Code with IF:

function saveCustomer(customer) {
  if (isCustomerValid(customer)) {
    database.save(customer)
  } else {
    alert('customer is invalid')
  }
}
Copy the code

Refactored code:

function saveCustomer(customer) {
  return isCustomerValid(customer)
    ? database.save(customer)
    : alert('customer is invalid')
}    
Copy the code

Use the ES6

const saveCustomer = customer =>
   isCustomerValid(customer)?
     database.save(customer) : alert('customer is invalid')    
Copy the code

Example 2

Code with IF:

function customerValidation(customer) { if (! customer.email) { return error('email is require') } else if (! customer.login) { return error('login is required') } else if (! customer.name) { return error('name is required') } else { return customer } }Copy the code

Refactored code:

const customerValidation = customer => ! customer.email ? error('email is required') : ! customer.login ? error('login is required') : ! customer.name ? error('name is required') : customerCopy the code

Example 3

Code with IF:

function getEventTarget(evt) { if (! evt) { evt = window.event; } if (! evt) { return; } const target; if (evt.target) { target = evt.target; } else { target = evt.srcElement; } return target; }Copy the code

Refactored code:

function getEventTarget(evt) {
  evt = evt || window.event;
  return evt && (evt.target || evt.srcElement);
}
Copy the code

2. Short-circuit operator

Case 1

Code with IF:

const isOnline = true;
const makeReservation= ()=>{};
const user = {
    name:'Damian',
    age:32,
    dni:33295000
};

if (isOnline){
    makeReservation(user);
}
Copy the code

Refactored code:

const isOnline = true;
const makeReservation= ()=>{};
const user = {
    name:'Damian',
    age:32,
    dni:33295000
};

isOnline&&makeReservation(user);
Copy the code

Example 2

Code with IF:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

if (active&&loan){
    sendMoney();
}
Copy the code

Refactored code:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

active && loan && sendMoney();

Copy the code

3. Function delegate:

Case 1

Code with IF:

function itemDropped(item, location) {
    if (!item) {
        return false;
    } else if (outOfBounds(location) {
        var error = outOfBounds;
        server.notify(item, error);
        items.resetAll();
        return false;
    } else {
        animateCanvas();
        server.notify(item, location);
        return true;
    }
}
Copy the code

Refactored code:

function itemDropped(item, location) { const dropOut = function() { server.notify(item, outOfBounds); items.resetAll(); return false; } const dropIn = function() { server.notify(item, location); animateCanvas(); return true; } return !! item && (outOfBounds(location) ? dropOut() : dropIn()); }Copy the code

4. Non-branching strategy

This technique tries to avoid using switch statements, instead creating a key/value map and using a function to access the value of the key passed as a parameter.

Case 1

Code with switch:

switch(breed){
    case 'border':
      return 'Border Collies are good boys and girls.';
      break;  
    case 'pitbull':
      return 'Pit Bulls are good boys and girls.';
      break;  
    case 'german':
      return 'German Shepherds are good boys and girls.';
      break;
    default:
      return 'Im default'
}
Copy the code

Refactored code:

const dogSwitch = (breed) =>({
  "border": "Border Collies are good boys and girls.",
  "pitbull": "Pit Bulls are good boys and girls.",
  "german": "German Shepherds are good boys and girls.",  
})[breed]||'Im the default';


dogSwitch("border xxx")
Copy the code

5. As a function of data

We know that function is the first class in JS, so we can use it to split our code into a function object.

Code with IF:

const calc = { run: function(op, n1, n2) { const result; if (op == "add") { result = n1 + n2; } else if (op == "sub" ) { result = n1 - n2; } else if (op == "mult" ) { result = n1 * n2; } else if (op == "div" ) { result = n1 / n2; } return result; } } calc.run("sub", 5, 3); / / 2Copy the code

Refactored code:

const calc = { add : function(a,b) { return a + b; }, sub : function(a,b) { return a - b; }, mult : function(a,b) { return a * b; }, div : function(a,b) { return a / b; }, run: function(fn, a, b) { return fn && fn(a,b); } } calc.run(calc.mult, 7, 4); / / 28Copy the code

6. Polymorphism

Polymorphism is the ability of an object to take multiple forms. The most common use of polymorphism in OOP is to use superclass references to refer to subclass objects.

Code with IF:

const bob = { name:'Bob', salary:1000, job_type:'DEVELOPER' }; const mary = { name:'Mary', salary:1000, job_type:'QA' }; Const calc = (person) =>{if (people.job_type==='DEVELOPER') return person. Salary +9000*0.10; If (people) job_type = = = 'QA') return person. The salary + 1000 * 0.60; } console.log('Salary',calc(bob)); console.log('Salary',calc(mary));Copy the code

Refactored code:

Const qaSalary = (base) => base+9000*0.10; Const devSalary = (base) => base+1000*0.60; //Add function to the object. const bob = { name:'Bob', salary:1000, job_type:'DEVELOPER', calc: devSalary }; const mary = { name:'Mary', salary:1000, job_type:'QA', calc: qaSalary }; console.log('Salary',bob.calc(bob.salary)); console.log('Salary',mary.calc(mary.salary));Copy the code

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: dev. To/damxipo/avo…


communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.