Skip to content

Commit caa487a

Browse files
committed
Add getNeighbours method
1 parent 12d89a2 commit caa487a

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

lib/fixed-2d-array.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,41 @@ Fixed2DArray.prototype.set = function(x,y,val) {
4242
this._grid[x][y] = val;
4343
};
4444

45+
/**
46+
* Returns all neighbours of the given coordinate.
47+
*
48+
* For example:
49+
* [ ][ ][ ][ ][ ]
50+
* [ ][*][*][*][ ]
51+
* [ ][*][X][*][ ]
52+
* [ ][*][*][*][ ]
53+
* [ ][ ][ ][ ][ ]
54+
*
55+
* the given coordinates are marked with an `X`
56+
* the function will return an array containing
57+
* the values for the fields maked with an `*`
58+
*/
59+
Fixed2DArray.prototype.getNeighbours = function(x,y){
60+
this.validateCoords(x,y);
61+
62+
var returnArray = [];
63+
64+
for(var i=x-1; i<=x+1; i++){
65+
for(var j=y-1; j<=y+1; j++){
66+
try {
67+
if(!(i===x && j===y)) {
68+
var element = this.get(i,j);
69+
returnArray.push(element);
70+
console.log('added',i,j);
71+
}
72+
}
73+
catch(e) {
74+
//this is a field at the edge of the grid.
75+
//ignore
76+
}
77+
}
78+
}
79+
return returnArray;
80+
};
81+
4582
module.exports = Fixed2DArray;

test/test.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,18 @@ test('get and set', function (t) {
1616
});
1717

1818
test('exception on index out of bounds', function (t) {
19-
t.plan(2);
19+
t.plan(3);
2020
var fa = new fixedArray(10,10);
2121
t.throws(function(){fa.get(10,10);});
2222
t.throws(function(){fa.get(-1,-1);});
23+
t.throws(function(){fa.getNeighbours(-1,-1);});
2324
});
25+
26+
test('get correct number of neighbours',function (t) {
27+
t.plan(3);
28+
var fa = new fixedArray(10,10);
29+
t.equal(fa.getNeighbours(5,5).length,8);
30+
t.equal(fa.getNeighbours(0,0).length,3);
31+
t.equal(fa.getNeighbours(1,0).length,5);
32+
});
33+

0 commit comments

Comments
 (0)