Browse the notebook

Category: functions

Random Choice

function randomChoice(...args:Array):*{
	return args[int(Math.random()*args.length)];
}

// choose randomly from a number of different values
var val:* = randomChoice(10, "Hello", "0xFF0000", 1000);

// choose a random color (in this case red, green or blue)
var randColor:uint = randomChoice(0xFF0000, 0x00FF00, 0x0000FF);

trace(val);
trace(randColor);

The function randomChoice() takes any number of arguments and spits one of them back randomly. Just a handy function to have around… I especially like to use this function to choose from a handful of colors.

Read snippet: Random Choice

Rect vs Ellipse

for (var i:int = 0; i<100; i++){
	graphics.lineStyle(0,0);
	graphics[["drawEllipse", "drawRect"][int(Math.random()*2)]](Math.random()*400, Math.random()*300, Math.random()*100,Math.random()*100)
}

/*
WARNING: This code was written for fun. Use at your own risk. 
*/

And a more readable version:

var methodChoices:Array = ["drawEllipse", "drawRect"];
var method:String;
var xp:Number, yp:Number, w:Number, h:Number;
for (var i:int = 0; i<100; i++){
	method = methodChoices[int(Math.random()*methodChoices.length)];
	graphics.lineStyle(0,0);
	xp = Math.random()*400;
	yp = Math.random()*300;
	w = Math.random()*100; 
	h = Math.random()*100;
	graphics[method](xp, yp, w, h)
}

/*
WARNING: This code was written for fun. Use at your own risk. 
*/

Here I use yesterdays associative array function call technique to do something different. Not really all that useful, but interesting….

Read snippet: Rect vs Ellipse

Associative Array Function Call

for (var i:int = 0; i<4; i++){
	this["phase"+i]();
}

function phase0():void{
	trace("phase 0");
}
function phase1():void{
	trace("phase 1");
}
function phase2():void{
	trace("phase 2");
}
function phase3():void{
	trace("phase 3");
}

/*
will output:
phase 0
phase 1
phase 2
phase 3
*/

/*
WARNING: This code was written for fun. Use at your own risk.
*/

I was pleasantly surprised back in the AS1 days… when I discovered that associative array syntax worked along with function calls (why wouldn’t it?). There are some interesting tricks you can do with this technique…. will post some later….

Read snippet: Associative Array Function Call

Function Returns a Function


appendExclamation("actionsnippit")("dot")("com")("is")("live");

function appendExclamation(str:String):Function{
  trace(str + "! ");
  return appendExclamation;
}

/* outputs:
actionsnippit!
dot!
com!
is!
live!
*/

This technique allows you to call a function more than once on one line. I first saw this used in the source files from a talk at flashcoders ny… I didn’t attend the talk, but stumbled on this interesting blog post awhile back http://www.flashcodersny.org/wordpress/?p=166.

This is a fun technique to use, I’ve found some unusual uses for it already… some of which you’ll see in later posts….

Read snippet: Function Returns a Function