Browse the notebook

Category: Object

Proxy – (object always defined)

This uses a proxy to make sure all keys/props of an object are always defined.

let spec = {
  get: (o, key) => {
    return o[key] != null ? o[key] : o[key] = O();
  },
  set: (o, key, v) => {
    o[key] = v;
  }
};

let O = () => {
  return new Proxy({}, spec);  
};

let dynamic = O();
dynamic.prop.creation = 'is interesting';
dynamic.prop.stuff.not.clear.what.this.could.be.used.for = 123;

// log out full structure
let f = (o) => {
  for (let i in o) {
    console.log(o[i]);
    if (typeof o[i] === 'object') f(o[i]);
  }
};
f(dynamic);

Outputs:

Proxy {creation: "is interesting", stuff: Proxy}
is interesting
Proxy {not: Proxy}
Proxy {clear: Proxy}
Proxy {what: Proxy}
Proxy {this: Proxy}
Proxy {could: Proxy}
Proxy {be: Proxy}
Proxy {used: Proxy}
Proxy {for: 123}
123
Read snippet: Proxy – (object always defined)

Color Breeder (aka Features)

Choose two colors to breed them and create 5 new colors:

This is a speed coded pen from awhile back – the features object is interesting – it allows two objects to be bred together. In this case two colors. I could see this is as part of some advanced/abstract colorpicker that allows the user to home in on a color.

Read snippet: Color Breeder (aka Features)

Loop Through All Properties of a Class

package {
	
	import flash.display.Sprite;
	import flash.utils.describeType;
	
	public class Main extends Sprite {
		
		public function Main(){
		    var test:Test = new Test();
			var desc:XML= describeType(test);
			// public vars
			for each (var v:XML in desc.variable){
				trace(v.@name, test[v.@name]);
			}
			// getters
			for each (v in desc.accessor){
				trace(v.@name, test[v.@name]);
			}
		}
		
	}
}

class Test{
	public var a:Number = 123;
	public var b:Number = 100;	 
	private var _getterVal:Boolean = false;
	public function get getter():Boolean{
		return _getterVal;
	}
}
/*
outputs:
b 100
a 123
getter false
*/

I’m working on a few libraries, QuickBox2D and a library for auto-generated UI stuff… this technique just came in handy. It shows how to use describeType() to loop through public vars and getters of a given class.

The title of this post should really be Loop Through All PUBLIC properties of a class…. but it was long enough as it is….
Note: this should be run as document class

Read snippet: Loop Through All Properties of a Class

Vector.sortOn()

var a:Vector.<Sprite> = new Vector.<Sprite>();

trace("unsorted");
for (var i:int = 0; i<10; i++){
	var s:Sprite = new Sprite();
	s.x = int(Math.random()*100);
	a.push(s);
	trace(s.x);
}

quickSortOn(a, "x", 0, a.length-1);

trace("sorted");
for (i= 0; i<10; i++){
	trace(a[i].x);
}

// modified code from kirupa.com
// http://www.kirupa.com/developer/actionscript/quickSort.htm
function quickSortOn(a:Vector.<Sprite>, prop:String, left:int, right:int):void {
    var i:int = 0, j:int = 0, pivot:Sprite, tmp:Sprite;
	i=left;
	j=right;
	pivot = a[Math.round((left+right)*.5)];
	while (i<=j) {
		while (a[i][prop]<pivot[prop]) i++;
		while (a[j][prop]>pivot[prop]) j--;
		if (i<=j) {
			tmp=a[i];
			a[i]=a[j];
			i++;
			a[j]=tmp;
			j--;
		}
	}
	if (left<j)  quickSortOn(a, prop, left, j);
	if (i<right) quickSortOn(a, prop, i, right);
}
/* outputs something like:
unsorted
26
33
20
63
7
68
75
39
67
53
sorted
7
20
26
33
39
53
63
67
68
75
*/

This demo is my first quick stab at using at a sortOn() function for the Vector class. It sorts a Vector of Sprites by their x property.

Recently there were a few times when I was prototyping ideas and suddenly realized that I needed to change my Vector to an Array because I needed to use sortOn().(If you don’t already know, there is no built in sortOn() method for the Vector class). In the past I spent some time with sorting algorithms, bubble, insertion etc… so I knew I could pretty easily write my own sortOn(), but I also realized that a generic implementation wouldn’t be easy/possible without loosing the type of the Vector. What I mean is, if you have a Vector of Sprites, you need a sorting method that takes a Vector.< Sprite > type as an argument (as seen above), if you have a Vector of TextFields you need a Vector.< TextField > type as an argument. You could of course use a generic type, but this kind of defeats the purpose of using a vector in the first place…

I will likely post a revised version of this in the near future with a slightly improved implementation of QuickSort. I haven’t spent that much time with this, but If I recall correctly this is not the ideal implementation. I ported this code from a nice Kirupa tutorial and modified it to sort based on a property…

Read snippet: Vector.sortOn()

var obj:Object = new Function()

var Pnt:Function = function(xp:Number, yp:Number){
	
	var x:Number = xp;
	var y:Number = yp
	
	this.setX = function(v:int):void{
		x = v;
	}
	this.setY = function(v:int):void{
		y = v;
	}
	this.getX = function():int {
		return x;
	}
	this.getY = function():int {
		return y;
	}
}

var p:Object = new Pnt(10,10);

trace(p.getX(), p.getY());
p.setX(100);
trace(p.getX());

/*
outputs:
10, 10
100
*/

Another way to define and instantiate Objects on the timeline. Interesting, but I don’t recommend it over actual classes…

Read snippet: var obj:Object = new Function()

Object.prototype Crap

Object.prototype.myVar = "I am a variable";

var s:Sprite = new Sprite();
 
trace(Object(s).myVar);

var v:Video = new Video();
trace(Object(v).myVar);

This…. should not be done… and setting myVar like this:

Object(s).myVar = "hello";

Will cause an error….

I keep a folder on my laptop for this website….. when I have a random snippet idea I put it in this folder…. Every couple of weeks I go through this folder and turn select snippets into posts…. when I rediscovered this snippet today it really made me laugh….

Read snippet: Object.prototype Crap

Set Multiple Properties

// set multiple properties of an Object 
function setProps(o:*, props:Object):void{
	for (var key:String in props){
		 o[key] = props[key];
	}
}

// example: 

var s:Sprite = new Sprite();
s.graphics.beginFill(0);
s.graphics.drawRect(0,0,10,10);
addChild(s);

// set some properties
setProps(s, {x:100, y:100, scaleX:2, scaleY:2, rotation:45});

This was inspired by tweening engines like TweenLite.

Basically the same thing using a with statement:

with(s) x = 100, y = 100, scaleX = 2, scaleY = 2, rotation = 45;
Read snippet: Set Multiple Properties

KeyCode Variables

// create constants for all letter and number keys:
var alphabet:Array = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var nums:Array = ["ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"];

var key:Object = new Object();
for (var i:int  = 0; i<alphabet.length; i++)
	 key[alphabet[i]] = 65 + i;
	 
for (i = 0; i<nums.length; i++){
	 var code:int = 48 + i;
     key[nums[i]]= code;
	 key[i] = code;
}
	 

// test them out
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onKeyPressed(evt:KeyboardEvent):void {
	if (evt.keyCode == key.A){
		trace("the a was pressed");
	}
	if (evt.keyCode == key.B){
		trace("the b was pressed");
	}
	if (evt.keyCode == key.NINE){
		trace("the 9 key was pressed");
	}
	if (evt.keyCode == key["0"]){
		trace("the 0 key was pressed");
	}
}

This is an easy way to store values for alphanumeric keys in variables that make sense… instead of having to do things like this:

// hit the zero key
if (evt.keyCode == 48){
   trace("the zero key was hit");
}
Read snippet: KeyCode Variables