math/WrappingGrid.js

import Grid from "./Grid.js";

/**
 * And "endless" wrapping grid
 * for example with a size 16x16 grid, accessing x:17 y:3 will reference x:1 y:3
 * @extends Grid
 */
class WrappingGrid extends Grid {
    /**
     * Wrap the coordinates of a vector in the grid
     * @param {Vector} v
     */
    wrapCoords(v) {
        v.x = v.x % this.w;
        v.y = v.y % this.h;

        if (v.x < 0) v.x = this.w + v.x;
        if (v.y < 0) v.y = this.h + v.y;
    }

    index(x, y) {
        x = x % this.w;
        y = y % this.h;

        if (x < 0) x = this.w + x;
        if (y < 0) y = this.h + y;

        return this.w * y + x;
    }
}

export default WrappingGrid