This is the 19th day of my participation in the More Text Challenge. For details, see more text Challenge

Prepare to write js skill series, basically summarize JS all sorts of practical small doohickey, small clever trick. This article focuses on how to make our functions clearer.

Object parameters use destruct

If you want the function to take many arguments (if more than two), then you should use an object. On this basis, deconstruction syntax can be used to extract the required parameters.

longhand

const greet = (obj) => {
  return `${obj.greeting}, ${obj.firstName}${obj.lastName}`;
}
Copy the code

rewrite

const greet = ({
  greeting,
  firstName,
  lastName
}) => {
  return `${greeting}, ${firstName}${lastName}`;
}
Copy the code

Using deconstruction is more elegant, and we can also write a lot less repetitive things, and the naming will be clearer.

Name the callback function

Good naming makes it easier to read the code, as does naming callback functions.

longhand

const arr = [1, 2, 3].map(a => a * 2);
Copy the code

rewrite

const double = a => a * 2;
const arr = [1, 2, 3].map(double);
Copy the code

It is obvious from the name that the callback function is used to double each element of the original array.

Make conditionals descriptive

For complex conditional statements, we can use functions alone to make the conditional statements more descriptive.

longhand

if (score === 100 || remainingPlayers === 1 || remainingPlayers === 0) {
    quitGame();
  }
Copy the code

rewrite

const winnerExists = () => {
  return score === 100 ||
    remainingPlayers === 1 ||
    remainingPlayers === 0
}
if (winnerExists()) {
  quitGame();
}
Copy the code

The way we wrote it, we had this long expression inside the parentheses, but it’s not so easy to see what it’s judging. So when we rewrite it, we put it in a named function, so we can sort of get a sense of what we’re saying.

Replace the switch statement with Map or Object

When your switch statements are long, it’s time to simplify your code

longhand

const getValue = (prop) => {
  switch (prop) {
    case 'a': {
      return 1;
    }
    case 'b': {
      return 2;
    }
    case 'c': {
      return 3;
    }
  }
}
const val = getValue('a');
Copy the code

Object to rewrite

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const val = obj['a'];
Copy the code

When we use switch to nest multiple blocks with multiple return statements just to get the return value of a given prop value, we can achieve the same effect with just one object.

The Map to rewrite

const map = new Map([['a', 1], ['b', 2], ['c', 3]])
const val = map.get('a')
Copy the code

When using Map, the code is also much shorter. We do this by passing an array, each item in the array contains a key and a value. Then, we just use the GET method of the Map instance to get the value from the key. One advantage of maps over objects is that we can use other values such as numbers, Booleans, or objects as keys. An object can only use a string or symbol as its key.

Use object.assign to set the default properties

longhand

const menuConfig = {
  title: null,
  body: 'Bar'
};
function createMenu(config) {
  config.title = config.title || 'Foo';
  config.body = config.body || 'Bar';
}
createMenu(menuConfig);
Copy the code

rewrite

const menuConfig = {
  title: 'Order',
  body: 'Send'
};
function createMenu(config) {
  config = Object.assign({
    title: 'Foo',
    body: 'Bar'
  }, config);
  // config : {title: "Order", body: "Bar"}
  // ...
}
createMenu(menuConfig);
Copy the code

Delete duplicate code and merge similar functions; Remove deprecated code

Bad way to write it

var paging = function( currPage ){ if ( currPage <= 0 ){ currPage = 0; jump( currPage ); }else if (currPage >= totalPage){currPage = totalPage; jump( currPage ); }else{jump(currPage); // Jump to}};Copy the code

rewrite

var paging = function( currPage ){ if ( currPage <= 0 ){ currPage = 0; }else if ( currPage >= totalPage ){ currPage = totalPage; } jump( currPage ); // Make the jump function independent};Copy the code

Refining function

If a function is so long that you have to add a few comments to make it more readable, then refactoring is necessary.

If there is a piece of code in the function that can be isolated, it is better to put that code in a separate function.

The sample

For example, in a function that is responsible for retrieving user information, we also need to print the log associated with the user information

var getUserInfo = function(){
    ajax( 'http:// xxx.com/userInfo', function( data ){
        console.log( 'userId: ' + data.userId );
        console.log( 'userName: ' + data.userName );
        console.log( 'nickName: ' + data.nickName );
    });
};

Copy the code

rewrite

We can wrap the print log statement in a separate function.

var getUserInfo = function(){
    ajax( 'http:// xxx.com/userInfo', function( data ){
        printDetails( data );
    });
};

var printDetails = function( data ){
    console.log( 'userId: ' + data.userId );
    console.log( 'userName: ' + data.userName );
    console.log( 'nickName: ' + data.nickName );
};
Copy the code

JavaScript Refactoring Tips — Making Functions good quality and Cleaner conditions in the life cycle

Just like it before you go! 🤞 🤞 🤞