Skip to content

Instantly share code, notes, and snippets.

@Phara0h
Last active April 5, 2016 19:37
Show Gist options
  • Save Phara0h/34a56d9dcf96ae35be15 to your computer and use it in GitHub Desktop.
Save Phara0h/34a56d9dcf96ae35be15 to your computer and use it in GitHub Desktop.
a fast grid algorithm class for things in 2d space
var SGHash = {
grid: new Array(new Array(new Array())),
insert: function(x, y, object)
{
x = ~~x;
y = ~~y;
if (!this.grid[x])
{
this.grid[x] = new Array();
}
if (!this.grid[x][y])
{
this.grid[x][y] = new Array();
}
this.grid[x][y].push(object);
},
searchOne: function(x, y)
{
return this.grid[~~x] && this.grid[~~x][~~y] || [];
},
// if oneresult is true it will return the first result it finds to go faster.
search: function(x1, y1, x2, y2, oneresult)
{
if (x2 == null || y2 == null)
return this.searchOne(x1, y1);
x1 = ~~x1;
y1 = ~~y1;
x2 = ~~x2;
y2 = ~~y2;
var xz = x2 - x1;
var yz = y2 - y1;
var found = [];
for (var i = xz + 1; i--;)
{
for (var j = yz + 1; j--;)
{
if (this.grid[x1 + i] && this.grid[x1 + i][y1 + j])
{
var points = this.grid[x1 + i][y1 + j];
if (!points)
points = [];
else if (oneresult)
return points;
for (var k = points.length; k--;)
{
found.push(points[k]);
}
}
}
}
return found;
},
remove: function(x, y, object)
{
x = ~~x;
y = ~~y;
if (this.grid[x] && this.grid[x][y])
{
this.grid[x][y].splice(this.grid[x][y].indexOf(object), 1);
//// For some reason, removing the empty arrays make chrome v8's engine go crazy on the memory managment.
//// Causing it to act like a memory leak and become way less memory efficient than if we just left them alone.
// if(this.grid[x][y].length == 0)
// {
// if(y > 0)
// this.grid[x].splice(y,1);
// else
// delete this.grid[x][y];
//
// if(Object.keys(this.grid[x]).length == 0 || this.grid[x].length == 0)
// {
// if(x > 0)
// this.grid.splice(x,1);
// else
// delete this.grid[x];
// }
// }
}
},
clear: function()
{
this.grid = new Array(new Array(new Array()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment