Browse the notebook

Category: associative arrays

Dictionary with ES6 Symbol

Creating a dictionary type object with ES6 Symbols is easy. Yes we have Maps and WeakMaps but this is still interesting for a variety of reasons… Being able to use objects as keys in another object (dictionary) has many great uses…. So how do you use Symbols like this?

let a = { id: Symbol('key') },
    b = { id: Symbol('key') };

let dictionary = {
  [a.id]: 'value by obj a',
  [b.id]: 'value by obj b'
};

console.log(dictionary[a.id]);
console.log(dictionary[b.id]);

// outputs:
// 'value by obj a'
// 'value by obj b'

By using either object a or object b’s `id` symbol, our dictionary points to another value. This old AS3 snippet is similar:

https://actionsnippet.com/?p=426

Read snippet: Dictionary with ES6 Symbol

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()

Multiple Keys

var key:Object = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
function onKeyPressed(evt:KeyboardEvent):void {
	key[evt.keyCode] = true;
	key.keyCode = evt.keyCode;
}
function onKeyReleased(evt:KeyboardEvent):void {
	key[evt.keyCode] = false
}

// example

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	
	//trace(key.keyCode);
	 
	if (key[Keyboard.LEFT]){
		trace("left");
	}
	
	if (key[Keyboard.RIGHT]){
		trace("right");
	}
	
	// keys #1, #2 and #3 are down
	if (key[49] && key[50] && key[51]){
		trace("one two thee");
	}
	
	// keys #6, #7, #8 and #9 keys are down
	if (key[54] && key[55] && key[56] && key[57]){
		trace("six seven eight nine");
	}
}

The first 10 lines of code make up this snippet. This is an easy way to keep track of multiple key presses. For games, this is the only key technique I use … wrapped up in a Singleton.

Read snippet: Multiple Keys

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