1
|
|
|
"use strict"; |
2
|
|
|
|
3
|
|
|
var Position = require('./position'); |
4
|
|
|
|
5
|
|
|
// Expose `Grid` |
6
|
|
|
|
7
|
|
|
module.exports = Grid; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Set up Grid with `topRightPos` |
11
|
|
|
* |
12
|
|
|
* Parameters: |
13
|
|
|
* |
14
|
|
|
* - `topRightPos` coordinates of the cell at the top right of the grid. ({x:1,y:1}) |
15
|
|
|
* |
16
|
|
|
* @param {Object} topRightPos |
17
|
|
|
* @api public |
18
|
|
|
*/ |
19
|
|
|
|
20
|
|
|
function Grid(topRightPos) { |
21
|
|
|
this.width = topRightPos.x; |
22
|
|
|
this.height = topRightPos.y; |
23
|
|
|
this.occupation = {}; |
24
|
|
|
|
25
|
|
|
this.isValid(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Types validator |
31
|
|
|
* |
32
|
|
|
* @api public |
33
|
|
|
*/ |
34
|
|
|
|
35
|
|
|
Grid.prototype.isValid = function() { |
36
|
|
|
if(!isCoordinates(this.width,this.height)) { |
37
|
|
|
throw new Error('Coordinates are not valid'); |
38
|
|
|
} |
39
|
|
|
}; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Save item's position inside the grid |
43
|
|
|
* |
44
|
|
|
* @param {Number} id |
45
|
|
|
* @param {Object} position |
46
|
|
|
* @api public |
47
|
|
|
*/ |
48
|
|
|
|
49
|
|
|
Grid.prototype.setItemPosition = function(id, position) { |
50
|
|
|
this.occupation[id] = position; |
51
|
|
|
}; |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Get cell occupation as a boolean |
56
|
|
|
* |
57
|
|
|
* @param {Object} position |
58
|
|
|
* @api public |
59
|
|
|
*/ |
60
|
|
|
|
61
|
|
|
Grid.prototype.getCellOccupation = function(position) { |
62
|
|
|
if(isPosition(position)){ |
63
|
|
|
for(var id in this.occupation){ |
64
|
|
|
if(this.occupation[id].x === position.x && this.occupation[id].y === position.y){ |
65
|
|
|
return parseInt(id); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
return null; |
69
|
|
|
} |
70
|
|
|
else { |
71
|
|
|
throw new Error('Position is not valid'); |
72
|
|
|
} |
73
|
|
|
}; |
74
|
|
|
|
75
|
|
|
|
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Coordinates validator helper |
79
|
|
|
* |
80
|
|
|
* @param {Number} x |
81
|
|
|
* @param {Number} y |
82
|
|
|
* @api protected |
83
|
|
|
*/ |
84
|
|
|
|
85
|
|
|
function isCoordinates(x,y) { |
86
|
|
|
return (x === parseInt(x, 10) && x > -1) && (y === parseInt(y, 10) && y > -1); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* Position validator helper |
92
|
|
|
* |
93
|
|
|
* @param {Object} position |
94
|
|
|
* @api protected |
95
|
|
|
*/ |
96
|
|
|
|
97
|
|
|
function isPosition(position) { |
98
|
|
|
return position instanceof Position; |
99
|
|
|
} |
100
|
|
|
|