Looking for a way to replicate the functionality of a switch case within an object literal function

When working with a switch case, the default case handles any scenarios that are not covered by the expected cases. To simplify my code and reduce cyclomatic complexity, I ended up replacing the switch case with an object literal function.

function test(){
  const options = getOptions();
  switch(options){
   case 'a':
       return 'foo';
   case 'b'
       return 'bar';
   default:
       return 'Nothing';
  }
}

The new function I created:

function test(){
  const options = getOptions();
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing'
   }[options]
}

test();

One concern was that any input other than 'a' or 'b' would result in undefined, unlike the switch case which could handle all other scenarios in the default case.

I attempted to address this issue using a regular expression like so:

function test(){
  const options = getOptions();
  const nonValidInput = new RegExp([^c-zC-Z], 'g');
   return {
      'a': 'foo',
      'b': 'bar',
      '': 'Nothing',
      null: 'Nothing',
      undefined: 'Nothing',
      nonValidInput: 'Nothing'
   }[options]
}

However, the scope of the above regular expression is not recognized inside the return statement, and the default case is not functioning as intended. Any suggestions on how to handle the default case effectively?

Answer №1

Consider giving this method a shot


function experiment(){
  const findings = {
      'x': 'hello',
      'y': 'world'
   }[gatherData()];
  return findings ? findings : 'Nada';
}

experiment();

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

Unit testing promises in Angular using Jasmine

My goal is to create a unit test that demonstrates the process of combining two promises using $q.all in Angular, and then confirming that both promises are resolved simultaneously. describe("Application controller", function() { var scope; var ...

Step-by-step guide on adding and removing a row from a table with the help of jquery and node js

I just finished creating a table in jade that includes two select boxes and a single text box. However, I encountered an issue where my row addition functionality stops working after the user makes a selection in the first select box and then changes the ...

Storybook encounters an undefined error with the Vuex store

Here is a snippet from my main.js file: import './plugins'; import store from './store'; import FileUpload from './components/FileUpload'; export default { install(Vue) { Vue.component('file-upload', ...

What could be the reason behind the unexpected behavior of my Bootstrap 3 carousel?

I'm attempting to replicate this visual effect in my own carousel, featuring semi-transparent images on the left and right sides. However, I'm encountering a negative result with my project when transitioning between slides at : here. This is th ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Displaying a variety of values based on the specific URL

I am attempting to display specific values from an array of objects based on the current URL. For example, if the URL is "localhost/#/scores/javelin," I only want to display the javelin scores from my array. Here is an example of what my array looks like: ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

LeafletJS and ReactJS integration causing misalignment in tile ordering

In my ReactJS single page application, I am utilizing the LeafletJS plugin to showcase a full-page map. Even after following the guidelines mentioned here, I am facing an issue where the map tiles are not displayed in the correct order and appear to be shu ...

Using jQuery UI Dialog with pjax for dynamic content loading

I'm currently utilizing pjax within a web application that incorporates jQuery UI dialogs. One issue I've encountered is that the div element responsible for creating the dialog gets displaced from its original container in the DOM once the dialo ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

What is the method for obtaining the root path of a Vue project during development mode?

Is there a way to retrieve the root path of a Vue project from the browser while using npm run serve? For example, the path may be E:\myApp\ Thank you in advance! I have attempted the following methods: process.cwd() returned /. require.resol ...

Turn off the div element until a radio button option is selected, then activate it

Is there a way to disable a div and then activate it only after selecting a radio button option? I know how to hide and show the div when an option is selected, but using the hidden property is not ideal. Can someone suggest a possible solution? <div ...

HTML is being incorrectly rendered by the Express framework

Looking to Use HTML as View Engine in Express? After going through the link, I attempted to start my server with an index.html file on port 8001. However, it failed to render correctly and showed an error in the console: Server Started Error: SyntaxError ...

Utilizing HTML Entities in jQuery

Is there a way to update the text of a submit button to display "Loading..." instead of "…" when clicked? Currently, I am encountering an issue where clicking the button still shows "…" instead of three dots. Below is the code snippet in qu ...

Translate unknown provider in Angular using $translateProvider

Here is the situation I am facing: I am working on an Ionic project and I want to implement internationalization using angular-translate. To achieve this, I have added angular-translate.min.js to my project: <script src="lib/ionic/js/ionic.bundle.js"&g ...

Is there a way to update the parameter name in an array.map function?

I'm a little unsure. Is there a way to dynamically change the marker parameter to marker1, marker2, marker3, and so on depending on the number of elements in the map? Currently, I have this code but I would like each element in the map to have a mark ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

What is the best method for comparing two elements effectively in JavaScript?

Check out this code snippet that ensures txtKeyword input is focused when a key is pressed by the user. var txtKeyword = document.getElementById("txtKeyword"); ... document.addEventListener("keypress", function(event) { if(event.src ...

Obtain data from ng-model in AngularJS $scope

I am using the angularjs framework to create a form.html and a controller.js. In the controller, I have a variable that retrieves the SSID of a box. My question is, how can I automatically assign the value of this variable in the input field of the form? I ...