Why optimize if.. else

In business development, people write a lot of junk code because of crazy requirements changes or time constraints, and then leave themselves with a TODO: optimize next time (actually forget later). .

And then one day the code goes wrong, and you go back and forth and say, oh, it makes you wonder about your life, so today we’re going to talk about if… Else how to optimize.

if (true) {
    if (true) {
        if (true) {
            if (true) {
                if (true) {
                    if (true) {}}}}}}Copy the code

From easy to difficult

You can’t do everything in one bite, so let’s start with the simplest optimization:

switch... case

Compared with the if… Else multiple nesting, switch… Case chain call is of course easier to understand and easier to maintain, when our conditions are relatively single but large we can simply use switch directly… Case:

const a = 3;
      
//bad:
if (a === 1) {
    consoel.log('a > 1');
}
if (a === 2) {
    consoel.log('a > 2');
}
if (a === 3) {
    consoel.log('a > 3');
}
if (a === 4) {
    consoel.log('a > 4');
}
// good:
switch(a) {
    case 1:
        console.log('a = 1');
    case 2:
        console.log('a = 2');
    case 3:
        console.log('a = 3');
    defaut:
        console.log('blablabla');
}
Copy the code

“, but this still makes us feel a little too much, after all, there are so many cases (funny), so the friends who love to do things need to think more.

useobject

I believe we all know very well, in the JS object is the use of key-value form to store data, and think we only have one parameter above the judgment condition, only need to determine whether the parameter is equal to a fixed value, then we can not do some articles on this? For example, use key to replace the judgment condition and value to replace the judgment when the condition is met:

const judegeMap = {
    1: () => { console.log('a = 1') },
    2: () => { console.log('a = 2') },
    3: () => { console.log('a = 3') },
    4: () => { console.log('a = 4') }
}

judgeMap[a]();
Copy the code

Look, this is better, but think about it, is it enough? In business development, the value of if is never just a fixed value, and the judgments can be weird, so let’s move on

Making a choice (decision tree)

Cough cough, seems to have said a great noun. We’re not going to talk about the concept of the term here, but we’re going to talk about something that looks something like this.

First look at our if… Else, if you think about it, it’s like a tree: it’s made up of a hierarchy of judgments and a hierarchy of judgments below and below:

if (a > b) {
    if (a > 10) {
        if(a < 22) { ... }... }if(b > 12) { ... }... }Copy the code

It can be seen from the above examples that our decision tree is composed of the top-level judgment: A > B and the subset judgment: A > 10, A < 22, b > 12. The execution of the whole tree only needs to pick the part that meets the judgment condition from it layer by layer. Then do it one by one. From this we can make the following optimizations:

function aIsBiggerThanb() {
    ...doSomething
}

function aIsBiggerThan10() {
    ...doSomething
}

function aIsSmallerThan22() {
    ...doSomething
}

function bIsBiggerThan12() {
    ...doSomething
}

const judgeArray = [
    {
        condition: a > b,
        callback: aIsBiggerThanb
    },
    {
        condition: a > b && a > 10,
        callback: aIsBiggerThan10
    },
    {
        condition: a > b && a > 10 && a < 22,
        callback: aIsSmallerThan22
    },
    {
        condition: a > b && b > 12,
        callback: bIsBiggerThan12
    }
];

const callbackArray = judgeArray.reduce((eventArray, item) => {
   item.condition &&  eventArray.push(item.callback)
   return eventArray;
}, [])

for (let id in callbackArray) {7lki9
    callbackArray[id]();
}
Copy the code

This can greatly increase the readability and maintainability of your code, but would then add more code, so in this case, I built a simple wheel to solve this problem, let we no longer need to manually write the decision tree and the correct decision process of harvesting you just need to focus on business logic

choicejs

install

You can install Choicejs through YARN or NPM

$ npm install choicejs
$ yarn add choicejs
Copy the code

require or import

const choicejs = require('choicejs').Choice;

import { Choice } from 'choicejs'
Copy the code

usage

add(description: string, condition: boolean, callback: any, extend? : string)

This method is used to increase your choices, there are four parameters, the description on behalf of your description of the currently selected, the don’t repeat, or increase the choice of coverage before and behind the second option is to determine conditions, the third generation refers to the callback method while judging condition, the final parameter as the optional parameters, generation refers to inherit from a description, Like the nested if… Else is nested like a condition.

A chestnut:

const judgeTree = new Choice();

const logAisBiggerThan1() {
  console.log('a > 1')}; constlogAisSmallerThan9() {
  console.log('a < 9');
}

const a = 3;

judgeTree
  .add('biggerThan1', a > 1, logAisBiggerThan1)
  .add('smallerThan9', a < 9, logAisSmallerThan9, 'biggerThan1')
Copy the code

use()

For simple and violent methods, add is used to define and use is used to implement. Without use, a defined decision tree is like a defined function, without () it has no use ~

Chestnut:

judgeTree.use(); // Note that judgeTree supports chained calls, so feel free to use() after add()Copy the code

destroy()

Simple destruction method, after use, you can choose to delete all information in the current instance, usually used as the last step, there is no example

For specific usage examples, you can refer to my Runkit sample code: Runkit Sample

conclusion

Although I shamelessly recommend my own wheel through the article, I hope you can still learn something from my superficial insights, if you like my article, please give me a thumbs up

(Of course, I am also very happy to click the star hahaha ~)

Choicejs source