Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor find* methods. Part 3/3 : Ban find<StructureType>() #237

Open
1 task
DiamondMofeng opened this issue Feb 26, 2023 · 0 comments
Open
1 task

Refactor find* methods. Part 3/3 : Ban find<StructureType>() #237

DiamondMofeng opened this issue Feb 26, 2023 · 0 comments
Labels
BREAKING CHANGE A breaking change would be introduced enhancement

Comments

@DiamondMofeng
Copy link
Member

Part 3 : Ban find<StructureType>()

!!!THIS IS A BREAKING CHANGE!!!

!!!THIS A BREAKING CHANGE!!!

This will not be easily merged. Feel free to give your idea on whether we should apply this to our next major version.

TODO

  • remove overloads about find<StructureType>()

To some point, find<StructureType>() is an explict assertion like as. It does not ensure that you are getting a correct type.

    {
        let towers = creep.pos.findInRange<StructureTower>([] as AnyStructure[], 2, {
            filter: (s)=> s.structureType===STRUCTURE_SPAWN,
        });
        towers[0].attack(creep);    // no error, it's on your own risk
    }

In most cases, you can implement some "safe" "Type Predicate Filter" to avoid mistakes. For example,
When filter is just used for structure types:

const isStructureType = <T extends StructureConstant>(structureType: T) => {
    return (structure: AnyStructure): structure is ConcreteStructure<T> => {
        return structure.structureType === structureType;
    };
};

let towers = creep.pos.findInRange([] as AnyStructure[], 2, {
    filter: isStructureType(STRUCTURE_TOWER),
});
towers[0].attack(creep);    // ok

for multiple structure types:

export function includes<T extends U, U>(arr: ReadonlyArray<T>, item: U): item is T {
  return arr.includes(item as T);
}

export function isStructureTypeAmong<T extends AnyStructure["structureType"]>(structureTypes: T[]) {
  return (s: AnyStructure): s is ConcreteStructure<T> => {
    return includes(structureTypes, s.structureType);
  }
}

However, when the conditions become complicated like filtering unfulfilled Spawn,Extension,Tower,..., you can either use an explict assertion, or implement some special "safe" "type predicate filters", like isStoreStructure. It's on your own.

@DiamondMofeng DiamondMofeng added enhancement BREAKING CHANGE A breaking change would be introduced labels Feb 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BREAKING CHANGE A breaking change would be introduced enhancement
Projects
None yet
Development

No branches or pull requests

1 participant