Jun
5
Quick and Dirty Associative Arrays in ActionScript
Original post by Mike Bukhin on see a puffin eat a fish
4:55 pm | Categorized: ITP 2007 (i)
One of the most basic data structures that I use frequently is an associative array — also known as a hash, map, or dictionary. Associative arrays allow for non-integer indexes. For example:
pup['stick'] = delicious
ActionScript 3 provides a dictionary object which isn’t very pleasant to use. You want to use a associative array for terseness but the native dictionary object has you write so much code that using it defeats the original purpose. I ended up rolling my own hash class which supports some basic functions (add, remove, key_exists, etc.) and that ended up being 77 lines of code. But using my associative array code was pretty dissatisfying, I still found myself traversing nested arrays to find my values.
Enter dynamic ActionScript. My old associative array class was 77 lines of code, here’s my new one:
dynamic public class map {}
By making a dynamic class, I can assign arbitrary properties to my class and treat those properties as keys in an associative array. So how does this work? Well to add a key I do
public var entries:map = new map();
entries['foo'] = bar;
That’s all there is to it. To retrieve the value I just do
myval = entries['foo'];
But wait a minute you say, how do I figure out if a value is set in my associative array? Well that’s easy too. Anything that isn’t set will have a value of undefined
if (entries['bar'] == undefined) { ... }
Finally, there’s even a way to iterate over all the keys even if you don’t know them in advance
for each (var entry:* in entries) { ... }
These small code snippets cover all of my needed functionality for associative arrays. Nesting dynamic classes are really readable. You can even use dot notation, namely
entries.foo = bar
but I prefer to use [] because then I can use numbers as keys.
entries.1 = bar // won't work
entries[1] = bar // will work
