ActionScript Hashmap
- October 1st, 2010
- Write comment
ActionScript allows defining dynamic classes which facilitate adding public properties and methods to them at run time. Internally these classes maintain a hash table for storing the properties and methods added at run-time.
Since ActionScript 3, a Dictionary class is available which allows for creating <key, value> mappings but it lacks the interface that, for example, C++’s std::map provides.
Adding properties at run-time can be leveraged to implement a very simple hashmap which, unfortunately, is not available in ActionScript.
Below is a class which can be used as a hashmap.
//HashMap.as import mx.collections.ArrayCollection; public dynamic class HashMap { private var size_:Number = 0; public function get size():Number { return size_; } /** * Inserts a new pair to the map */ public function insert(key:String, value:Object):void { // Only increment counter if the // item is not already in the map. if (!this.hasOwnProperty(key)) { size_++; } this[key] = value; } /** * Removes an element from the map */ public function erase(key:String):void { // Only decrement counter if the item is in the map. if (this[key]) { size_--; } delete this[key]; } /** * Removes all elements from the map */ public function clear():void { for (var key:String in this) { delete this[key]; } size_ == 0; } /** * Returns the element identified by key `key` */ public function getItem(key:String):Object { return this[key]; } /** * Returns the element at index `index` */ public function getIemAt(index:int):* { var i:int = 0; for (var key:String in this) { if (i == index) { return this[key]; } ++i; } return null; } /** * Check if the map contains any elements */ public function empty():Boolean { return size == 0; } }
UPDATE (11/01/2010):
Thanks to a suggestion by Craig W, I have updated the code of HashMap class. The `size()` method has been replaced by property `size`. Also the `erase()` and `clear()` methods have been updated. They now use the `delete` operator to remove properties instead of setting the properties to `null` which was causing the `size()` method to return incorrect result.