Big brother, you may not need switch for JavaScript

Translation: www.valentinog.com/blog/switch...

By Valentino

Translated by: Huang Fangao

Not happy without "switch"

The big guys in Java like switch very much, and so do JavaScript developers. To be honest, our developers are lazy and it's easy for people like me who lack creativity to stick to the status quo.

switch is convenient: given an expression, we can check whether it matches other items in a bunch of case clauses. Consider the following example:

const name = "Juliana";

switch (name) {
  case "Juliana":
    console.log("She's Juliana");
    break;
  case "Tom":
    console.log("She's not Juliana");
    break;
}

Copy code

When the name is Juliana, we will print a message and immediately exit break by. When the switch is inside the function, break can be omitted as long as you return from each clause.

When there is no match, you can also have a default branch:

const name = "Kris";

switch (name) {
  case "Juliana":
    console.log("She's Juliana");
    break;
  case "Tom":
    console.log("She's not Juliana");
    break;
  default:
    console.log("Sorry, no match");
}

Copy code

switch is widely used in Redux reducers through Redux Toolkit Simplify the template and avoid a lot of if statements

const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGIN_FAILED = "LOGIN_FAILED";

const authState = {
  token: "",
  error: "",
};

function authReducer(state = authState, action) {
  switch (action.type) {
    case LOGIN_SUCCESS:
      return { ...state, token: action.payload };
    case LOGIN_FAILED:
      return { ...state, error: action.payload };
    default:
      return state;
  }
}
Copy code

Not bad, no problem, but can we have a better choice?

Learn from Python

This one from Telmo Tweets It caught my attention. He shows two "switch" styles, one of which is very close to a similar pattern in Python.

Python doesn't have a switch, it can teach us a better alternative to our favorite chaotic switch. First let's port the code from JavaScript to Python:

LOGIN_SUCCESS = "LOGIN_SUCCESS"
LOGIN_FAILED = "LOGIN_FAILED"

auth_state = {"token": "", "error": ""}


def auth_reducer(state=auth_state, action={}):
    mapping = {
        LOGIN_SUCCESS: {**state, "token": action["payload"]},
        LOGIN_FAILED: {**state, "error": action["payload"]},
    }

return mapping.get(action["type"], state)
Copy code

In Python, we can simulate switch using a dictionary. This default case is replaced by dict.get().

When a key does not exist, a KeyError may appear in Python

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

>>> my_dict["not_here"]

# Output: KeyError: 'not_here'
Copy code

This. get() method is a more secure alternative to accessing directly through the key value, because it does not cause errors, and can specify default values for nonexistent keys:

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

>>> my_dict.get("not_here", "not found")

# Output: 'not found'
Copy code

So this line in Python:

# omit
    return mapping.get(action["type"], state)
Copy code

In JavaScript, it is equivalent to:

function authReducer(state = authState, action) {
// omit
    default:
      return state
}
Copy code

Let's use the same Python style code in JavaScript.

Replace switch

If we want to get rid of switch, we can do this:

function authReducer(state = authState, action) {
  const mapping = {
    [LOGIN_SUCCESS]: { ...state, token: action.payload },
    [LOGIN_FAILED]: { ...state, error: action.payload }
  };

  return mapping[action.type] || state;
}
Copy code

It seems so refreshing. Thanks to modern JavaScript and the emergence of object computing property values in ES2015, we should also thank you for such excellent feedback Expansion syntax The appearance of... state can be directly expanded, simplified and clearer.

Do you like this treatment? Of course, compared with switch, it has some limitations. At least for a reducer, it may be a more concise technique.

Thank you for reading!

Tags: Python Javascript Java

Posted on Sun, 26 Apr 2020 19:03:46 -0700 by rilitium