Skip to content

Commit bc16c78

Browse files
committed
Merge pull request phaserjs#1187 from codevinsky/feature/group-filter
Group.filter
2 parents 9546fc2 + 8300787 commit bc16c78

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

src/core/Group.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,7 @@ Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
795795
{
796796
return false;
797797
}
798-
798+
799799
if (Phaser.Utils.getProperty(child, key) !== value)
800800
{
801801
return false;
@@ -1205,6 +1205,36 @@ Phaser.Group.prototype.postUpdate = function () {
12051205

12061206
};
12071207

1208+
1209+
/**
1210+
* Allows you to obtain a Phaser.ArrayList of children that return true for the given predicate
1211+
* For example:
1212+
* var healthyList = Group.filter(function(child, index, children) {
1213+
* return child.health > 10 ? true : false;
1214+
* }, true);
1215+
* healthyList.callAll('attack');
1216+
* Note: Currently this will skip any children which are Groups themselves.
1217+
* @method Phaser.Group#filter
1218+
* @param {function} predicate - The function that each child will be evaluated against. Each child of the Group will be passed to it as its first parameter, the index as the second, and the entire child array as the third
1219+
* @param {boolean} [checkExists=false] - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
1220+
* @return {Phaser.ArrayList} Returns an array list containing all the children that the predicate returned true for
1221+
*/
1222+
Phaser.Group.prototype.filter = function(predicate, checkExists) {
1223+
var index = -1,
1224+
length = this.children.length,
1225+
result = new Phaser.ArrayList();
1226+
1227+
while(++index < length) {
1228+
var child = this.children[index];
1229+
if(!checkExists || (checkExists && child.exists)) {
1230+
if(predicate(child, index, this.children)) {
1231+
result.add(child);
1232+
}
1233+
}
1234+
}
1235+
return result;
1236+
};
1237+
12081238
/**
12091239
* Allows you to call your own function on each member of this Group. You must pass the callback and context in which it will run.
12101240
* After the checkExists parameter you can add as many parameters as you like, which will all be passed to the callback along with the child.

0 commit comments

Comments
 (0)