Skip to content

Commit 298622f

Browse files
committed
added: Group.filter
takes a predicate function and passes child, index, and the entire child array to it. return an ArrayList containing all children that the predicate returns true for.
1 parent bb8da11 commit 298622f

1 file changed

Lines changed: 32 additions & 1 deletion

File tree

src/core/Group.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
788788
{
789789
return false;
790790
}
791-
791+
792792
if (Phaser.Utils.getProperty(child, key) !== value)
793793
{
794794
return false;
@@ -1198,6 +1198,37 @@ Phaser.Group.prototype.postUpdate = function () {
11981198

11991199
};
12001200

1201+
1202+
/**
1203+
* Allows you to obtain a Phaser.ArrayList of children that return true for the given predicate
1204+
* For example:
1205+
* var healthyList = Group.filter(function(child, index, children) {
1206+
* if(child.exists && child.health > 10) {
1207+
* return true;
1208+
* }
1209+
* });
1210+
* healthyList.callAll('attack');
1211+
* Note: Currently this will skip any children which are Groups themselves.
1212+
* @method Phaser.Group#filter
1213+
* @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
1214+
* @param {boolean} [checkExists=false] - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
1215+
*/
1216+
Phaser.Group.prototype.filter = function(predicate, checkExists) {
1217+
var index = -1,
1218+
length = this.children.length,
1219+
result = new Phaser.ArrayList();
1220+
1221+
while(++index < length) {
1222+
var child = this.children[index];
1223+
if(!checkExists || (checkExists && child.exists)) {
1224+
if(predicate(child, index, this.children)) {
1225+
result.add(child);
1226+
}
1227+
}
1228+
}
1229+
return result;
1230+
};
1231+
12011232
/**
12021233
* 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.
12031234
* 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)