Skip to content

Instantly share code, notes, and snippets.

@hyoshida
Last active January 13, 2016 10:29
Show Gist options
  • Save hyoshida/2ddb6760351cd46407ac to your computer and use it in GitHub Desktop.
Save hyoshida/2ddb6760351cd46407ac to your computer and use it in GitHub Desktop.
Extensions for Vector and Array in ActionScript 3
var bob:Person = new Person(name: "bob");
var john:Person = new Person(name: "john");
var alice:Person = new Person(name: "alice");
var vectorPersons:Vector<Person> = new Vector.<Person>[bob, john, alice];
VectorUtil.of(vectorPersons).getOneBy({ name: "bob" });
//=> #<Person name: "bob">
var arrayPersons:Array = [bob, john, alice];
arrayPersons.findBy({ name: "bob" });
//=> [#<Person name: "bob">]
Array.prototype.findBy = function(attributes:Object):Array {
return VectorUtil.of(this).findBy(attributes);
};
Array.prototype.setPropertyIsEnumerable("findBy", false);
Array.prototype.getOneBy = function(attributes:Object):Array {
return VectorUtil.of(this).getOneBy(attributes);
};
Array.prototype.setPropertyIsEnumerable("getOneBy", false);
public class VectorUtil {
private var _vector:*;
public static function of(vector:*):VectorUtil {
var vectorUtil:VectorUtil = new VectorUtil;
vectorUtil._vector = vector;
return vectorUtil;
}
public function findBy(attributes:Object):* {
return _vector.filter(function(element:Object, _index:int, _source:*):Boolean {
for (var key:String in attributes) {
var value:* = attributes[key];
if (element[key] != value) {
return false;
}
}
return true;
});
}
public function getOneBy(attributes:Object):Object {
for each (var element:Object in _vector) {
var found:Boolean = true;
for (var key:String in attributes) {
var value:* = attributes[key];
if (element[key] != value) {
found = false;
break;
}
}
if (found) {
return element;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment