Is there any alternatives to a huge switch, with multiple cases and fallthrough in JavaScript?

javascript switch vs object performance
javascript switch multiple case
js case fallthrough
dynamic switch case javascript
javascript switch case best practice
javascript switch multiple variables
javascript switch return
async/await in switch case javascript

I need to map some user generated fields to something the system I'm working on can recognize.

For this we want to provide a certain amount of freedom for users, and offer five or so options for each of our fields.

So far we have a switch which does the job, but now we have to extend the switch, and it's going to be pretty big. This is needless to say not a very dynamic way of doing it. Is there any alternatives?

function findHeader(object) {
  var title = object.toString().trim().toLowerCase()
  switch (title) {
    case 'name':
    case 'idea':
    case 'ide':
    case 'ide navn':
    case 'title':
    case 'idea name':
      title = 'name'
      break
    case 'beskrivelse':
    case 'problemet':
    case 'description':
    case 'the problem':
    case 'ide beskrivelse':
      title = 'description'
      break
    case 'ejer':
    case 'owner':
    case 'opfinder':
    case 'ide person':
    case 'idea person':
    case 'person':
      title = 'owner'
      break
    case 'duedate':
    case 'deadline':
    case 'tidsfrist':
    case 'sidste dato':
    case 'dato':
    case 'due date':
      title = 'duedate'
      break
    case 'billede':
    case 'billeder':
    case 'image':
    case 'images':
    case 'attachment':
      title = 'imageUrl'
      break
    case "":
      title = 'remove'
      break
    default:
      title = 'Unassigned'
      break
  }
  return title
}

Perhaps an object?

const titles = {
  'name':        ['name', 'idea', 'ide', 'ide navn', 'title', 'idea name'],
  'description': ['beskrivelse', 'problemet', 'description', 'the problem', 'ide beskrivelse'],
  'owner' :      ['ejer', 'owner', 'opfinder', 'ide person', 'idea person', 'person'],
  'duedate' :    ['duedate', 'deadline', 'tidsfrist', 'sidste dato', 'dato', 'due date'],
  'imageUrl' :   ['billede', 'billeder', 'image', 'images', 'attachment']
}
const getKey = (obj,val) => Object.keys(obj).find(key => obj[key].indexOf(val) !=-1 );

function findHeader(object) {  
  var title = object.toString().trim().toLowerCase();
  return getKey(titles,title) || 'Unassigned' 
}

console.log(
  findHeader("Owner"),
  findHeader("Bla")
)  

JavaScript - switch, How do I put multiple conditions in a switch case? 🖥️ An alternative to if/else and switch in JavaScript. May 01, 2015 in JavaScript. I don’t intend to replace them for all their use case. It would be dumb. The alternative won’t change the way it works and its purpose is mostly code aesthetic.

You can store datas in array of object and search values in it instead of switch

let arr = [
  {
    "title": "name",
    "values": ['idea','ide','ide navn','title','idea name']
  },
  {
    "title": "description",
    "values": ['beskrivelse','problemet','description','the problem','ide beskrivelse']
  },
  {
    "title": "owner",
    "values": ['ejer','owner','opfinder','ide person','idea person','person']
  },
];    

function findHeader(object) {
  let title = object.toString().trim().toLowerCase(),
      res = arr.filter(val => val.values.includes(title));    
  return res.length ? res[0].title : "Unassigned";
}

console.log(findHeader("problemet"));
console.log(findHeader("ide person"));
console.log(findHeader("opfinderrr"));

What's wrong with the switch statement in JavaScript?, Some alternative remedies to the (mostly) problematic switch/case statement utility comes with large disclaimers, most of which forcibly limit the power of a Misaligned fallthrough cases; Multiple cases can run, making it  If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch. I'd love a different syntax for fallbacks in switches, something like, errr..

You can use a regular expression with an object to get the value of an item based on a string of keys:

const titles = {
  "name|idea|ide": "name",
  "beskrivelse|problemt|description|the problem": "description"
};

const get_item = item => titles[Object.keys(titles).find(key => new RegExp(`(\\||^)${item}(\\||$)`).test(key))];

let title = "problemt";
title = get_item(title); // Get the associated value from the key
console.log(title);

An alternative approach to switch statements in Javascript : javascript, An alternative approach to switch statements in Javascript Using eslint the issue with lack of break (no-fallthrough error ) and the lack of parenthesis in switch (no-case-declarations error ) are easily countered. I've written multiple custom eslint rules to help me start adopting newer ES features instead of using old ones. Switching Details. If multiple cases matches a case value, the first case is selected.. If no matching cases are found, the program continues to the default label.. If no default label is found, the program continues to the statement(s) after the switch.

The solutions others have posted are great and elegant if one expects not too much data.

If performance is crucial and you have huge dictionaries, and/or a lot of terms to replace (order of magnitude 100k or more pieces of data), then your original solution using switch and case statements will be the best one, especially if you put the assignment line and the break statement after every singe case (making it even uglier). The problem is that you cannot dynamically update that at runtime.

But if dynamic updates is not what you need, you can save this monster of a switch statement into a separate script file as a function, out of sight, keeping your code tidy.

The point is, while the use of JavaScript objects is much more elegant, I wouldn't completely discount the switch & case solution, depending on the application.

How to avoid switch-case syndrome – James Padolsey, This is the first post of a hopeful series dubbed “JavaScript, tip of the week“; I will try Using multiple if-else clauses doesn't seem appropriate so the switch Using a lookup table as an alternative to the Switch statement is not new; large number of pre and post conditions and honestly it's cleaner syntax  The expression used in a switch statement must have an integral or character type, or be of a class type in which the class has a single conversion function to an integral or character type. There can be any number of case statements within a switch. Each case is followed by the value to be compared to and after that a colon.

Replacing switch statements with Object literals, In many programming languages, the switch statement exists - but should it any longer? If you're a JavaScript programmer, you're often jumping in and out There are multiple issues with switch , from its procedural control flow to its We'​re forced to manually add break; statements within each case  Problems with switch. There are multiple issues with switch, from its procedural control flow to its non-standard-looking way it handles code blocks, the rest of JavaScript uses curly braces yet switch does not. Syntactically, it’s not one of JavaScript’s best, nor is its design.

Rethinking JavaScript: Eliminate the switch statement for better code , Now I'm going try to convince you to eliminate the switch statement. It's not Immutable, it can't be composed with other functions, and it's a little side effecty. function switchcase (cases, defaultCase, key) { boys and girls we can decompose this switch to multiple reusable methods, and we all know… This type of switch can be considered as an alternative to multiple if else clauses. Fallthrough. In Go, the control comes out of the switch statement immediately after a case is executed. A fallthrough statement is used to transfer control to the first statement of the case that is present immediately after the case which has been executed.

A Case Against Switches, The default fallthrough behavior is begging for errors. You're matching a single key, the case, with a single value, an expression to be evaluated, or a set of instructions. How do we use a JavaScript object in place of a switch? Objects in JavaScript give you a simple alternative to the switch statement. Since there's no break, we have a fallthrough to case 6, which has an empty statement list. We thus fall out of the switch statement and resume normal control flow afterwards. If value is 6 , there won't be any console output at all because this case has an empty statement list.

Comments
  • please add example for the input also
  • How about this? stackoverflow.com/questions/35769144/…
  • You can just create a map. You can store it as a separate JSON file if it is dynamic and big. Personally, Personally for me this "certain amount of freedom" sounds more like ambiguity and confusion. Why would someone want to build a service which allows multiple different names for the same thing and creates a fishy map to handle user's invalid data for him. IMHO :)
  • We switched to a system where the label is decoupled from the fieldname. So we offer our users only the fieldname: 'name', 'description' and such, and then let them define any label name they want as tied to the standardized name. So kinda like the opposite of your current method. The big advantage is that you don't need to hard code all the different spellings of the same concept, since the user will ad those themselves to the JSON file / database / data store.
  • This seems to work, but can you please explain the getKey? I don't quite understand what's going on there.
  • It loops over the object returning the key if the array contains the name
  • Thank you, this seems like a clean solution that fits our needs.
  • Not sure where the need for the Proxy lies, but i like the regex idea :)