I'm writing a simple JavaScript game, which uses a 2-dimensional array as the main data structure. I wrote this function-class-thing that allows me to give any two integers, positive or negative. This class should "wrap" those integers back onto the game grid.
For example:
var g = new Grid(10, 10)
g.set(15, -2, "hello")
g.get(5, 8); //should be "hello"
Anyway, I'm striving to improve my JavaScript, so I'm wondering if there are any improvements (performance, "javascriptness", etc.) that I might be able to make.
var Grid = (function(w, h){
this._width = w;
this._height = h;
this._grid = new Array((this._width * this._height) | 0);
this.get = function(x, y){
var coords = _normalize(x, y);
return this._grid[(coords.y * coords.x) + coords.x];
}
this.set = function(x, y, item){
var coords = _normalize(x, y);
this._grid[(coords.y * coords.x) + coords.x] = item;
}
this._normalize = function(x, y){
if(x < 0) x = (this._width + x) % this._width;
else if(x >= this._width) x = x % this._width ;
if(y < 0) y = (this._height + y) % this._height;
else if(y >= this._height) y = y % this._height;
return {'x': x, 'y': y};
}
});