This is the 7th day of my participation in Gwen Challenge

Logical statements we use everyday are if… else… And the switch… case… , the do… while… And so on.

In simple scenarios, we may have little sense of the performance of these grammars, but in complex business scenarios, if handled poorly, there can be a lot of nested logic that is unreadable and difficult to extend.

The journey of a thousand miles begins with the first step. Writing high maintainability and high quality code, we need to start with the details, and today we will focus on how to optimize logical judgment code in JavaScript.

Nested hierarchy optimization

function supply(fruit, quantity) {
    const redFruits = ['apple'.'strawberry'.'cherry'.'cranberries'];
    // Condition 1: fruit exists
    if (fruit) {
        // Condition 2: belong to red fruit
        if (redFruits.includes(fruit)) {
            console.log('Red fruit');
            // Condition 3: the quantity of fruit is more than 10
            if (quantity > 10) {
                console.log('Quantity > 10'); }}}else {
        throw new Error('No fruit! '); }}Copy the code

From the above example, we can see that the judgment process is orderly and corresponds to the mapping of the real world. However, because the code layer is nested, it is difficult to read and maintain.

If the fruit parameter is passed in, each execution requires at least two if judgments, and there are performance issues.

Let’s optimize the above code:

function supply(fruit, quantity) {
    const redFruits = ['apple'.'strawberry'.'cherry'.'cranberries'];
    if(! fruit)throw new Error('There's no fruit.');     // Condition 1: Handle the error ahead of time when Fruit is invalid
    if(! redFruits.includes(fruit))return// Condition 2: Return early if the fruit is not red

    console.log('Red fruit');

    // Condition 3: the quantity of fruit is more than 10
    if (quantity > 10) {
        console.log('Quantity > 10'); }}Copy the code

The main optimization of the nesting level is to terminate the unqualified conditions in advance, reduce the three layers of nesting to one layer, simplify the code result structure, and enhance the readability.

Optimization of multi-conditional branches

Many of us are familiar with the following code, right? (Think about when you first started coding.)

function pick(color) {
    // Choose fruit according to color
    if (color === 'red') {
        return ['apple'.'strawberry'];
    } else if (color === 'yellow') {
        return ['banana'.'pineapple'];
    } else if (color === 'purple') {
        return ['grape'.'plum'];
    } else {
        return[]; }}Copy the code

One rule we need to know is that if else is better for conditional interval judgment, while switch case is better for branching of specific enumerated values.

We use switch… case… Let’s rewrite this:

function pick(color) {
    // Choose fruit according to color
    switch (color) {
        case 'red':
            return ['apple'.'strawberry'];
        case 'yellow':
            return ['banana'.'pineapple'];
        case 'purple':
            return ['grape'.'plum'];
        default:
            return[]; }}Copy the code

switch… case… The optimized code looks neat and clear, but it’s still verbose. Continue to optimize:

  • With the help ofObjectThe {key: value} structure of theObjectEnumerates all the cases, and then uses key as the index, directly throughObjectThe key orObject[key] to get the content:
const fruitColor = {
    red: ['apple'.'strawberry'].yellow: ['banana'.'pineapple'].purple: ['grape'.'plum'],}function pick(color) {
    return fruitColor[color] || [];
}
Copy the code
  • useMapData structures, real (key, value) key-value pairs:
const fruitColor = new Map()
    .set('red'['apple'.'strawberry'])
    .set('yellow'['banana'.'pineapple'])
    .set('purple'['grape'.'plum']);

function pick(color) {
    return fruitColor.get(color) || [];
}
Copy the code

After optimization, the code is cleaner and easier to extend.

For better readability, you can also define objects more semantically and use array.filter to achieve the same effect:

const fruits = [
    {name: 'apple'.color: 'red'},
    {name: 'strawberry'.color: 'red'},
    {name: 'banana'.color: 'yellow'},
    {name: 'pineapple'.color: 'yellow'},
    {name: 'grape'.color: 'purple'},
    {name: 'plum'.color: 'purple'}];function pick(color) {
    return fruits.filter(f= > f.color == color);
}
Copy the code

conclusion

The examples and methods used above are quite elementary, but the ideas are worth our attention. I hope you can gain something from them!

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Everybody is good! I am the author of programming Samadhi, yi Wang, my public account is “programming Samadhi”, welcome to pay attention to, I hope you can give me more advice!

Knowledge and skills should be paid equal attention to, internal force and external power should be repaired simultaneously, theory and practice should grasp both hands, both hands should be hard!