Upgrade from using a switch statement to a more robust pattern in JavaScript

I am looking to enhance my app by dynamically displaying pages based on a user's type and role properties. Currently, I am using a simple switch statement that determines the view based on the user's type, like this:

switch(type) {
  case 'a':
    return CONSTANT.ONE;

  case 'b':
    return CONSTANT.TWO;

  default:
    return null;
}

While this switch statement works for now, it is not ideal for scalability as the number of types and roles increases. Can anyone recommend a more effective pattern to handle this scenario? I considered using a state pattern, but I am unsure if that is too complex for simply returning a string. Any suggestions would be greatly appreciated.

Thank you.

Answer №1

In a scenario similar to @MarkusJarderot's approach, I have a slightly different method with key distinctions in functionality:

const keyMap = {
    'x': VALUE.ONE,
    'y': VALUE.TWO,
    'default': null
};

return keyMap.hasOwnProperty(option) ? keyMap[option] : keyMap["default"];

Even when the value of keyMap[option] evaluates to falsy, this method will still return it instead of defaulting to null. This feature proves beneficial especially when handling values like 0 or an empty string.

Answer №2

Utilize an object for quick referencing:

let categories = {};

You can then include categories like so:

categories['x']=CONSTANT.ONE;

and access them like this:

let yyy = categories['x'];

By using this method, you can easily manage categories in various parts of your code

Answer №3

If you're looking for a versatile solution, consider implementing the Strategy Pattern:

//In the absence of the strategy pattern
gameDifficulty(difficulty) {
  switch(difficulty){
    case 'easy':
      easyGameMode();
      break;
    case 'difficult'
      difficultMode();
      break;
  }
}

// Implementing Strategy
const strategies = {
  easy: easyGameMode(),
  difficult: difficultGameMode(),
  //Additional strategies can be added here
  __default__: normalGameMode()
}

const easyGameMode = (game) => {
  game.difficulty(1);
  //Implement actions specific to easy game mode here
  return game;
}

const normalGameMode= (game) => {
  game.difficulty(2);
  //Implement actions for normal game mode here
  return game;
}

const difficultGameMode = (game) => {
  game.difficulty(3);
  //Implement actions for difficult game mode here
  return game;
}

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

For further details on this concept, check out this informative article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the style of the legend from bars to a line chart in chart.js version 2.4.0

https://i.sstatic.net/BXcXj.pngI'm currently using chart.js version 2.4.0 for displaying graphs, and I'm having trouble changing the legend style from bar to line. Is there a way to switch the legend display from bar to line in chart.js? Here i ...

Ways to extract specific HTML from a jQuery element

When fetching html from a website, how can I extract specific html content instead of getting all of it? I have attempted the following method: Before appending data to the target below container.html(data); I would like to perform something like data.f ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

Exploring the World with GPS Technology and Coding

Starting off, I am looking to develop a web-based or browser-based application in the near future. The goal is to incorporate a GPS module as part of the interface for a self-hosted application on tablets or laptops, utilizing the data for tracking purpo ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

How can I create a customized scrollbar for a div element in an Angular 2.0 CLI project?

I am attempting to create a sleek horizontal scroll bar within one of my div elements, similar to the example shown here: https://i.stack.imgur.com/ziWhi.png My project is based on the angular2 CLI. Progress so far: I came across this package angular2-s ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

Is the default behavior of Ctrl + C affected by catching SIGINT in NodeJS?

When I run my nodejs application on Windows, it displays ^C and goes back to the cmd prompt when I press Ctrl + C. However, I have included a SIGINT handler in my code as shown below: process.on('SIGINT', (code) => { console.log("Process term ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

When a button is clicked, load two separate pages into two distinct divs at the same time

$('#menuhome').click(function(){ $('#leftcolumncontainer').load('pages/homemenu.php'); }); the code above is used to load the home menu on the left side. Now, let's add the following: $('#menu ...

javascript display an alert when the page is loaded

My customer wants to display an alert upon visiting a website. The problem is, alerts pause the page loading until the user clicks "Ok," and the client needs the page to continue loading in the background while the alert is visible. We could create a cus ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

Unexpected disappearance of form control in reactive form when using a filter pipe

Here is a reactive form with an array of checkboxes used as a filter. An error occurs on page render. Cannot find control with path: 'accountsArray -> 555' The filter works well, but the error appears when removing any character from the fi ...

Establishing a recurring interval when the component mounts for a specified period of time

I have read through several Q&As on this topic, but I am still unable to pinpoint what mistake I am making. The code snippet below is meant to display a countdown in the console and update the DOM accordingly, however, it only prints 0s in the console ...

Discover how to retrieve full response data by entering text into a text field using Reactjs

I am encountering an issue while retrieving values from rendered data in a component that has already been displayed on the page. I want to input data into a text field and have it sent to the database, but using the runtime data from that specific field. ...

I am struggling with grasping the concept of the event system

I'm encountering an issue with the following code snippet: <template> <div class="chart" v-bind:style="chartStyleObject" v-on:mousedown.left="initHandleMousedown($event)" v-on:mouseup.left="initHandleMouseu ...