skip to Main Content

So I’ve come across some of my old code, which is something like :

const valStore = {
  val1: "val1"
  val2: "val2"
  val3: "val3"
}

And it then is calls this like so:

switch (val) {
  case "val4":
    function()
  break;
  case "val5":
    coolFunction()
  break;
  case valStore[val]:
    otherFunction(val)
...

I don’t like that there is an entire object with identical keys & values it seems messy as it’s only 5 values in the real version, although a fall-through switch statement doesn’t seem much better:

switch (val) {
  case "val4":
    function()
    break;
  case "val5":
    coolFunction()
    break;
  case "val1":
  case "val2":
  case "val3":
    otherFunction(val)
...

I’ve considered using sets and an else if, I’m not sure about if I want a replacement or if I’m wasting my time. It just got me thinking.

2

Answers


  1. Alternatively to the switch, you could put the function references in the object and invoke them directly:

    const valStore = {
      val1: otherFunction,
      val2: otherFunction,
      val3: otherFunction,
      val4: function() { /* your logic here */ },
      val5: coolFunction
    }
    
    valStore[val]();
    

    I would also suggest finding a way to remove the valX: otherFunction duplication, but without knowing the context and structure of your logic it’s difficult to suggest a workable alternative.

    Login or Signup to reply.
  2. it would be best to use a dictionary with functions instead of switch or if else statements

    const val = "val1"; // set the value here, dynamically or hard coded
    // store your functions into an easy to access dictionary.
    const valStore = {
        "val1": otherFunction1,
        "val2": otherFunction2,
        "val3": otherFunction3,
        "val4": () => { /* your code here */ },
        "val5": otherFunction5,
    }
    
    // call it like this, this also checks if the val belongs to a valid function
    
    let output = valStore[val] ? valStore[val]() : "No function ran";
    

    Language

    there are two ways to do language

    Version 1

    have each language then its string value for said text

    let lang = {
       "en":{
          "hi":"Hi"
       },
       "de":{
          "hi":"Hallo"
       }
    };
     
    // then you can do
    let hiText = lang['de']['hi'];
    

    Version 2

    have each string and its language version

    let lang = {
       "hi":{
          "en":"Hi",
          "de":"Hallo"
       }
    };
     
    // then you can do
    let hiText = lang['hi"]['de'];
    

    I Prefer Version 2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search