This has come up a few times in a project I’m working on, how can I “test” a switch to determine if it has a case in it without actually executing it?
If the case has to be run, is there an efficient way to check?
Thank you in advance.
i.e.
if (runSwitch(switch.hasCase("casename2"))) {
alert("I've got it!");
}
else {
alert("nope");
}
function runSwitch(case) {
switch (case) { // Any way to skip the function?
case "casename0" : alert("case"); break;
case "casename1" : alert("case"); break;
case "casename2" : alert("case"); break;
case "casename3" : alert("case"); break;
}
}
Since David Schwartz didn’t post an answer, I’m going to post my solution (it’s hardly a solution) and a demo and explanation of his solution as I understand it.
My solution:
I simply stopped using switches and switched to JSON (arrays) since the only purpose of my switch was to set variables depending on the input.
When using an array, checking to see if a “case” exists is easy (just run
arrayVar["casename"], it returns undefined if it doesn’t exist) and you don’t need to clog up the namespace with extra variables, running code is slightly more difficult as it needs to be provided as a string andevaled but overall this works much better for me.There’s no need to post a demo or code since it really isn’t a solution to this issue.
David Schwartz’s solution:
Demo: http://jsfiddle.net/SO_AMK/s9MhD/
Code:
Explanation: The code above is commented as needed.