Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby case-when vs JavaScript switch-case

I come from Ruby world and entering the JavaScript world. One feature of Ruby language is the case statements to evaluate a target value:

my_val = case my_var
           when "var1" then "value1"
           when "var2" then "value2"
           else "value3"
         end

# my_val evaluated to a specific value 
puts my_val

Can I do something as succinct in JavaScript as above? This is the closest I get:

let myVal = null;
switch (myVar) {
  case "var1": 
    myVal = "value1";
    break;
  case "var2":
    myVal = "value2";
    break;
  default:
    myVal = "value3";
}

// my_val evaluated to a specific value 
console.log(myVal);
like image 390
Jimmy Chu Avatar asked Mar 04 '23 10:03

Jimmy Chu


1 Answers

You could use an object with a ternary to set a default value like so:

const obj = {
  "var1":"value1",
  "var2":"value2",
  "defaultVal": "value3" // default value
},
getVal = sVar => sVar in obj ? obj[sVar] : obj["defaultVal"];

// Use case 1:
console.log(getVal("var1")); // get "var1" from the object

// Use case 2:
console.log(getVal("foo")); // get "foo" from the object, doesn't exsist, so we get the default value

The above creates an object, where each key in the object points to a value (ie what myVar should turn into). If myVar is not in the object, it will default to defaultVal, if it is in the object it will retrieve the associated value.

like image 64
Nick Parsons Avatar answered Mar 08 '23 23:03

Nick Parsons