Search code examples
javascriptvue.jsvuex

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?


Solution

  • 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.