Last active
January 13, 2016 10:29
-
-
Save hyoshida/2ddb6760351cd46407ac to your computer and use it in GitHub Desktop.
Extensions for Vector and Array in ActionScript 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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">] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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