Snippets

Conditional switch

	switch (true) {
		case inst is A : //do A things; break;
		case inst is B : //do B things; break;
		case inst is C : //do C things; break;
	}

Binary search for nearest smaller value of an Ascending sorted Array of Numbers

public static function findNearest(arr: Array, value: int): int {
	var n : int = arr.length;

	var l : int = 0; //left
	var r : int = n - 1; //right

	var vl	: Number = arr[l];
	var vr	: Number = arr[r];

	if (vl >= value) return 0;
	if (vr <= value) return n - 1;

	var m : int = r >> 1; //middle
	var vm	: Number = arr[m];

	while (l < m) {// && m < r : don't need to check this
		if (value == vm) return m; //already correct value found

		if (value < vm) {//left
			r	= m;
			vr	= vm;
		} else {//right
			l	= m;
			vl	= vm;
		}
		m = (r + l) >> 1;
		vm = arr[m];
	}

	return value<vr ? l : r;//at this point (m==l && r==m+1) or (m==l+1 && r=m)
}

Windows / Mac OS color correction

stage.colorCorrection = ColorCorrection.ON;

//clone an Object via constructor

new (sampleMC.constructor as Class)();

//deep copy

var buffer:ByteArray = new ByteArray();
buffer.writeObject(value);
buffer.position = 0;

registerClassAlias( "my.package.Book", Book );
var bookCopy:Book = Book( buffer.readObject() );
var sprite:Sprite = new Sprite();
trace(getQualifiedClassName(sprite)); // "flash.display::Sprite"
trace(getQualifiedSuperclassName(sprite)); // "flash.display::DisplayObjectContainer"
trace(getDefinitionByName("flash.display::Sprite")); // [class Sprite]
//bezier curve equation
//x0, x2 : pivot points
//x1 : control point
//xc : center point
x(t) = (x0-2*x1+x2)*t*t + 2*(x1-x0)*t + x0;

//find center point xc (t = 0.5)
xc = (x0+x2)/4+x1/2;

//find control point x1
x1 = 2*xc - (x0+x2)/2;

Leave a comment