I have a class containing two methods. The first takes a callback function and loops over a set of values, and for each that satisfies a condition it executes the callback with two parameters:
...
public mapShapeMatrix(callback): void {
let row = 0, col = 0;
for (let bit = 0x8000; bit > 0; bit = bit >> 1) {
if (this.dirs[this.currentDir] & bit) {
callback(col, row);
}
if (++col === 4) {
col = 0;
++row;
}
}
}
...
I then have another method which calls the first and passes it a callback:
...
private collide(boardMatrix): boolean {
this.mapShapeMatrix(
(col: number, row: number) => {
if ((boardMatrix[row + this.offset.y] &&
boardMatrix[row + this.offset.y][col + this.offset.x]) !== 0) {
return true;
}
}
)
return false;
}
...
Then later on I am calling the collide function to check whether it returned true or false:
if (this.collide(boardMatrix)) {
// do stuff
}
The problem is, as expected, that the callback returns true within its own scope, and does not return from the collide function. Normally I would solve this with a closure pattern, but it's not so easy with TypeScript. Storing the call to this.mapShapeMatrix in a variable means that the collide function is not returning a boolean, and if its return type is not a boolean then the call to this.collide complains about checking for truthiness against the wrong type.
Essentially I'm looking to find out if there is a way in TypeScript to write this kind of pattern, and if not, is there a different solution?