Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Refactoring if else statement

Here is my method:

Object.entries(query).forEach(([key, value]) => {
  if (key === 'team_ids') {
    if (typeof value === 'string') {
      this.items.push(this.$store.getters.teamById(value));
    } else {
      value.forEach((itemId) => {
        this.items.push(this.$store.getters.teamById(itemId));
      });
    }
else if (key === 'close_ids') {
    if (typeof value === 'string') {
      this.items.push(this.$store.getters.closeFriendsById(value));
    } else {
      value.forEach((friendId) => {
        this.items.push(this.$store.getters.closeFriendsById(friendId));
      });
    }
  } else {
    if (key === 'name') this.name = value;
    if (key === 'patr') this.patr= value;  
  }
});

I am trying to refactor it but now i'm stumped...
It don't looks good. Any advice?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can refactor if statements with a switch statement.

Try this:

Object.entries(query).forEach(([key, value]) => {
  switch(key) {
    case 'name' : 
      this.name = value; break;
    case 'patr' : 
      this.patr = value; break;
    default:
      let getterMap = {
        'team_ids': 'teamById',
        'close_ids': 'closeFriendsById'
      }
      if(Array.isArray(value)) {
        value.forEach((itemId) => {
          this.items.push(this.$store.getters[getterMap[key]](itemId));
        });
      } else {
        this.items.push(this.$store.getters[getterMap[key]](value));
      }
      break;
  }
});

You can add more keys in getterMap if you want to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...