I am getting a undefined value for a recursive Switch Statement when the mode is random. The idea is that is the most id random, it would randomly select a number and set a new mode and return the original switch statement.
Everthing works fine when the mode is not in random. So I am not sure what is wrong here.
variable a is the mode, while i,j are simply numbers.
switchMode: function (i, j, a){
var b;
console.log(a);
switch(a) {
default:
case 'add':
console.log(i, j);
b = i + j;
break;
case 'minus':
console.log(i, j);
b = i - j; //negative numbers possible
break;
case 'multiply':
console.log(i, j);
b = i * j; //0 possible
break;
case 'random':
this.randomSwitchMode(i, j);
break; //random
}
return b;
},
randomSwitchMode: function(i, j) {
var c = Math.ceil(Math.random() * 3);
console.log(i, j, c);
switch(c) {
default:
case 1:
var a = 'add';
console.log(a);
this.switchMode(i, j, a);
break;
case 2:
var a = 'minus';
console.log(a);
this.switchMode(i, j, a);
break;
case 3:
var a = 'multiply';
console.log(a);
this.switchMode(i, j, a);
break;
}
}
You’re not returning anything from “randomSwitchMode”. Even if you do that, you’ll also have to make sure you assign its return value to “b” in “switchMode”.
Thus the random cases should look like:
and then in “switchMode”:
Since you’re going to all this trouble anyway, I offer the suggestion that instead of using a
switchstatement you keep an object that maps operation names to functions:You could split the “random” case out and handle it differently I guess. The overall point is that while there’s nothing inherently wrong with a
switchstatement, basing the implementation on a data structure is going to be more flexible.