Skip to content

Instantly share code, notes, and snippets.

@strager
Created March 22, 2012 19:09
Show Gist options
  • Save strager/2161880 to your computer and use it in GitHub Desktop.
Save strager/2161880 to your computer and use it in GitHub Desktop.
AS3 Dictionary replacement
// AS3 Dictionary replacement
//
// Patterns to replace:
//
// import flash.utils.Dictionary;
// => import io.spaceport.util.Dictionary;
//
// var dict:Dictionary;
// => var dict:Map;
//
// var dict:Dictionary = new Dictionary(/* ... */);
// => var dict:Map = new Map(/* ... */);
//
// dict[x] = y;
// => dict.set(x, y);
//
// y = dict[x];
// => y = dict.get(x);
//
// delete dict[x];
// => dict.unset(x);
//
// x in dict
// => dict.contains(x);
//
// for (var key in dict)
// => for each (var key in dict.keys)
//
// for each (var value in dict)
// => for each (var value in dict.values)
//
package io.spaceport.util {
public final class Map {
private var _keys:Array = new Array();
private var _values:Array = new Array();
public function Map(weakKeys:Boolean = false) {
// TODO Support weakKeys
}
public function get keys():Array {
return _keys.slice();
}
public function get values():Array {
return _values.slice();
}
public function set(key:*, value:*):void {
var index:int = _keys.indexOf(key);
if (index >= 0) {
_values[index] = value;
} else {
_keys.push(key);
_values.push(value);
}
}
public function unset(key:*):void {
var index:int = _keys.indexOf(key);
if (index >= 0) {
_keys.splice(index, 1);
_values.splice(index, 1);
}
}
public function get(key:*):* {
var index:int = _keys.indexOf(key);
if (index >= 0) {
return _values[index];
} else {
return undefined;
}
}
public function contains(key:*):Boolean {
return _keys.indexOf(key) >= 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment