AS3 Helper Class – Wrap()

We are building an AS3 Helper class to speed up development on Actionscript 3 projects. Feel free to use these methods in your own Helper class, or to share your own methods that you find useful.

Wrap()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Helper
{
	/**
	 * This method reigns in a value to keep it between
	 * the supplied minimum and maximum limits.
	 * Useful for wrapping number values 
	 * (particularly paginated interfaces).
	 * Returns the reigned-in result.
	 */
	public static function Wrap(theValue:*, 
				  minLimit:*, maxLimit:*):*
	{
		var result:* = theValue
		if (theValue < minLimit)
		{
			result = maxLimit;
		} else if (theValue > maxLimit) {
			result = minLimit;
		}
		return result;
	}
}

Usage

1
2
3
4
5
6
7
var minLimit:uint = 0;
var maxLimit:uint = 20;
 
var pageIndex:uint = 20;
 
pageIndex = Helper.Wrap(++pageIndex, minLimit, maxLimit);
// pageIndex = 0.  Hooray!  That's a Wrap!

Comments

i find myself doing this kind of thing all the time: checking to see if a number has gone out of bounds, and wrapping it back to the minimum or maximum limit i’ve set. i build many, many projects with paginated interfaces, where you click the Back or Next arrow buttons to flip the page. Clicking Next on the last page sends you to the first page, while clicking Back on the first page wraps you back around to the last page. The Wrap method helps reduce some code clutter and a bit of typing.

Of course, it’s not bulletproof. i cheated a bit by using the * wildcard for the datatypes. i did this so that the method will tolerate various numeric datatypes without complaining. Pass a string, a boolean and an array to this method all at once to see it break.

For more AS3 Helper Classses and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

Leave a Reply

Your email address will not be published. Required fields are marked *