An efficient method for testing intersections is using a hash table. This technique is commonly employed in advanced algorithms to detect collisions within the ODE system.
The process involves dividing the space into a grid, where each cell contains a list of objects that intersect with it. Initialization of this grid is done by scanning through all objects using python-like pseudocode since I'm not familiar with javascript.
for each ob in objects:
for each x in [floor(ob.x_min / grid_size) .. floor(ob.x_max / grid_size)]:
for each y in [floor(ob.y_min / grid_size) .. floor(ob.y_max / grid_size)]:
hashtable[hash(x, y)].append(ob)
To identify collisions involving a specific object, near-collisions are looked up in the hash table and an exact collision test is then performed on each one.
near_collisions = []
for each x in [floor(ob.x_min / grid_size) .. floor(ob.x_max / grid_size)]:
for each y in [ceil(ob.y_min / grid_size) .. ceil(ob.y_max / grid_size)]:
near_collisions = near_collisions ++ hashtable[hash(x, y)]
remove duplicates from near_collisions
for each ob2 in near_collisions:
if exact_collision_test(ob, ob2):
do_something