Skip to content Skip to sidebar Skip to footer

Replace Switch With A Better Pattern (javascript)

I have to upgrade my app to display pages based on a users type and role properties. Currently I employ a simple switch statement to do this based on user type, e.g. switch(type) {

Solution 1:

Very similarly to @MarkusJarderot, but with a few important differences in behavior, I would use:

var mapping = {
    'a': CONSTANT.ONE,
    'b': CONSTANT.TWO,
    '_default': null
};

return mapping.hasOwnProperty(type) ? mapping[type] : mapping["_default"];

When the value of mapping[type] is falsy, this will still return it, rather than going to the null alternative. That will be very helpful when one of your values is 0 or an empty string.

Solution 2:

Use an object as a lookup:

var roles = {};

Then you can add roles like this:

roles['a']=CONSTANT.ONE;

and look them up like this:

var xxx = roles['a'];

This way you can add things to the roles in different places in your code

Solution 3:

You can use Strategy Pattern:

//Example without strategy patterngameDifficulty(difficulty) {
  switch(difficulty){
    case'easy':
      easyGameMode();
      break;
    case'difficult'difficultMode();
      break;
  }
}

// Using Strategyconst strategies = {
  easy: easyGameMode(),
  difficult: difficultGameMode(),
  //More strategies__default__: normalGameMode()
}

consteasyGameMode = (game) => {
  game.difficulty(1);
  //Do easy game mode stuff in herereturn game;
}

constnormalGameMode= (game) => {
  game.difficulty(2);
  //Do normal game mode stuff in herereturn game;
}

constdifficultGameMode = (game) => {
  game.difficulty(3);
  //Do difficult game mode stuff in herereturn game;
}

conststartGame = (game, difficulty) => {
  const gameModifier = strategies[difficulty] ?? strategies.__default__;
  returngameModifier(game, difficulty);
}

More info in this article.

Post a Comment for "Replace Switch With A Better Pattern (javascript)"