Welcome to WebmasterWorld Guest from 54.242.53.253

Forum Moderators: open

Message Too Old, No Replies

switch problem

using output of random function

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

Junior Member

5+ Year Member

joined:July 4, 2007
posts:112
votes: 0


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
2:01 pm on May 28, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


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(){
...
11:59 pm on May 28, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:July 4, 2007
posts:112
votes: 0


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()} ?
2:59 am on May 29, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


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);
5:34 am on May 29, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:July 4, 2007
posts:112
votes: 0


Thanks! I can see it now.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members