Welcome to WebmasterWorld Guest from 54.167.5.15

Forum Moderators: open

Message Too Old, No Replies

switch problem

using output of random function

     

ctoz

9:53 am on May 28, 2011 (gmt 0)

5+ Year Member



I have a function which chooses randomly between four other functions:

function choose(){
var choices = [func1, func2, func3, func4],
randomnumber = Math.floor(Math.random() * choices.length);
choices[randomnumber]();
}


The next step is to say, "if the outcome is func1(), do this..." for each of the four possible outcomes. I think it needs a switch function, but I'm not sure about some of the codeómarked "?":

function branches() {
var a = ? func1
var b = ? func2()
var c = ? func3
var d = ? func4

switch( ? ) {
case ?func1:
doThis(); doThat(); return false;
break
case ?func2:
doThat(); doTother(); return false;
break
case ?func3:
doTother(); doSome(); return false;
break
default:
doSome(); doThis(); return false; }
}

I'll be trying things out, but someone might shorten my evening shift...

cheers

daveVk

2:01 pm on May 28, 2011 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



I think just need to declare the 4 functions

function choose(){
var choices = [func1, func2, func3, func4],
randomnumber = Math.floor(Math.random() * choices.length);
choices[randomnumber]();
}

function func1(){
doThis(); doThat();
}

function func2(){
...

ctoz

11:59 pm on May 28, 2011 (gmt 0)

5+ Year Member



OKóbut: what if the process is to be repeated? so that you're running choose() three or four times in succession? wouldn't these need switch to distinguish one run from another?

Or thinking out loud, maybe better to do variations on choose(), like choose2() {//same as choose() }, choose3() {//same as choose()} ?

daveVk

2:59 am on May 29, 2011 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



I do not see any problem calling choose() any number of times.

If the choices need to change each time, like not calling same function twice, then consider adding a parameter rather than having variant functions.

function choose(choices){
randomnumber = Math.floor(Math.random() * choices.length);
choices[randomnumber]();
}

var functs = [func1, func2, func3, func4];
choose(functs);

ctoz

5:34 am on May 29, 2011 (gmt 0)

5+ Year Member



Thanks! I can see it now.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month