Martin Erlic
Martin Erlic

Reputation: 5667

Functional switch statement in Javascript

Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;          
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}

How can I get this to work?

Upvotes: 1

Views: 1773

Answers (5)

SBUK-Tech
SBUK-Tech

Reputation: 1337

Javascript functional switch statement that allows lambda pattern matching

const switchF = (c, options, def) => {
  const choice = options.find(([key, ]) => {
    if (Array.isArray(key)) {
      return key.indexOf(c) >= 0;
    }
    if (typeof key === "function") {
      return key(c);
    }
    return key === c;
  });
  if (!choice) return def();
  const [, choiceVal] = choice;
  if (typeof choiceVal === "function") return choiceVal();
  if (typeof choiceVal === "string") {
    return switchF(choiceVal, options, def);
  }
  throw Error("switch F Failed!");
};

Example use:


const switcher = (c) =>
  switchF(
    c,
    [
      ["foo", () => "Foo option"],
      ["bar", "foo"],
      [(v) => v > 3, () => 99],
    ],
    () => "DEFAULT"
  );

console.log(switcher("foo")); // returns 'Foo'
console.log(switcher("bar")); // returns 'Foo
console.log(switcher(4)); // returns '99'
console.log(switcher(2)); // returns 'DEFAULT'
console.log(switcher("zzz")); returns 'DEFAULT'

Upvotes: 0

Feathercrown
Feathercrown

Reputation: 2591

@Bergi's answer is the best approach, but if you can't change the way your code-message combos are stored, and the variables are globals, you can use:

scriptletResult=window["code"+myData];

Upvotes: 1

user7813357
user7813357

Reputation:

var yourStatusCode = 300; //function get300();
var data = "MyData"; //function data();

function runner(){
    switch(data){
        case "MyData":
        myFunc();
        return "hola data we are looking for!";
        break;
        case "DataNumberTwo":
        return "this is data number 2";
        break;
        default:
        return "WOAH what data is this??";
        break;
    }

}

console.log(runner());

Upvotes: 0

Bergi
Bergi

Reputation: 664936

You'll want to use a lookup map for that, instead of multiple variables:

var codes = {
    1: "This is a summary",
    300: "This is a note"
};

With that you can do

if (statusCode in codes) {
    scriptletResult = codes[statusCode];
} else {
    scriptletResult = codes[1];
}

Upvotes: 4

Jonas Wilms
Jonas Wilms

Reputation: 138417

var myData=300;
var code1="This is a summary";
var code300=" this is a note";
var result=(function(){
switch(myData) {
case 1:
    return code1;        
case 300:
   return code300,
default:
    return "not defined";
}
})();

alert(result);

Perfect usecase for an IIFE + switch combo.

However best would be:

alert([code1,code2][myData]);

Upvotes: 1

Related Questions