showing results for - "reach to each cell in 2d array javascript"
Elena
01 Jun 2018
1// ... Matrix declaration goes here
2
3function getCell(matrix, y, x) {
4  var NO_VALUE = null;
5  var value, hasValue;
6  
7  try {
8    hasValue = matrix[y][x] !== undefined;
9    value    = hasValue?  matrix[y][x] : NO_VALUE;
10  } catch(e) {
11    value    = NO_VALUE;
12  }
13
14  return value;
15}
16
17function surroundings(matrix, y, x) {
18  // Directions are clockwise
19  return {
20    up:        getCell(matrix, y-1, x),
21    upRight:   getCell(matrix, y-1, x+1),
22    right:     getCell(matrix, y,   x+1),
23    downRight: getCell(matrix, y+1, x+1),
24    down:      getCell(matrix, y+1, x),
25    downLeft:  getCell(matrix, y+1, x-1),
26    left:      getCell(matrix, y,   x-1),
27    upLeft:    getCell(matrix, y-1, x-1)
28  }
29}