RoomPosition.findClosestByRange () filtering broken?



  • I had this kind of code (creeps is an Array):

    var courier = creep.room.findClosestByRange (creeps, {
        filter: function (possibleTarget)
        {
            debugger;
            return 
            (
                possibleTarget !== creep
                && possibleTarget.memory.role === creep.memory.role
                && possibleTarget.carry.energy < possibleTarget.carryCapacity
                && creep.pos.getDirectionTo (possibleTarget) !== directionAway
            );
        } 
    })
    

    The filter function was never called and thus no filtering occured. I changed the code for a test, and the following worked fine:

    var courier = creep.pos.findClosestByRange (creep.room.myCreeps.filter (function (possibleTarget)
    {
        debugger;
        return possibleTarget !== creep
            && possibleTarget.memory.role === creep.memory.role
            && possibleTarget.carry.energy < possibleTarget.carryCapacity
            && creep.pos.getDirectionTo (possibleTarget) !== directionAway;
    }));
    


  • P.S - It happens only when passing an array of objects. And creep.room.myCreeps is a defined property of Room, which returns an Array of me creeps.



  • This is a very common mistake Javascript beginners do. You need to hand over a function reference not the function call. I explained it here:Stackoverflow. Try it the second way, and it sould work.



  • @chris Sorry, but there are no calls of 'filter' in the first example. There I pass an object with a property called 'filter' which holds a function definition. Do I miss something?