Can i include a function call into a filter?



  • Hello! I'm the guy monopolizing the forum last weeks ^^!

    I have a function to unload energy, and i'm trying to include a feature on it. I splitted my links into linksFrom and linksTo and stored their ids in memory. And now i want my creeps to be able to unload energy under certain conditions only in linksFrom.

    This is what i had...

    target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: function(structure) {
            return (
                (structure.structureType == STRUCTURE_LINK)
                //bla bla...
            );
        }
    });
    

    And this is what i'm trying to do....

    target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: function(structure) {
            return (
                (structure.structureType == STRUCTURE_LINK && this.IsValid(structure))
                //bla bla...
            );
        }
    });
    //Where IsValid() is...
    IsValid: function(structure){
        let links = creep.room.memory.linksFrom;
        for(let i in links){
            if(structure.id == links[i]){
                return true;
            }
        }
    }
    

    I tried like this and throws an error but...is it possible to include a call to a function inside a filter? Or...is there any simpler way to do this?



  • Since you don't have many links it is vastly cheaper to just get those and set a memory flag on those if they are sending or receiving. Then you sort them by distance or even cache the one corresponding to the source you are mining.

    That snippet you posted is really a CPU hog.



  • Hello everyone,

    I'm posting here because this looks like a similar issue to me. My intention is to call findClosestByParh(), but i want to exclude from the results those what are included in an array:

    //I have an array called myArray with a few IDs
    let myArray = ['1234', '2345', '3456'];
    let myStructure = creep.pos.findClosestByPath(FIND_MY_STRUCTURES, {
        filter: function(s){    
            return ((s.structureType == STRUCTURE_SPAWN || s.structureType == STRUCTURE_EXTENSION)
            //This weird line is what i'd like to include in the filter.
            && s.id "is not present in" myArray);
        }
    });
    

    Is this possible?



  • @calfa You can use lodash function includes so your code should look like :

    //I have an array called myArray with a few IDs
    let myArray = ['1234', '2345', '3456'];
    let myStructure = creep.pos.findClosestByPath(FIND_MY_STRUCTURES, {
        filter: function(s){    
            return ((s.structureType == STRUCTURE_SPAWN || s.structureType == STRUCTURE_EXTENSION) && !_.includes(myArray,s.id));
        }
    });
    
    😍


  • @flyasd1 i love you! Thank you so much!

    I've been trying o google it for a while, but didn't even know how to do the search.

    👌