-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgrid-utils.js
70 lines (61 loc) · 1.36 KB
/
grid-utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const _ = require("lodash");
/**
* @typedef {Array.<Array>} Grid
*/
/**
* @typedef {Object} Cell
* @property value
* @property {number} x
* @property {number} y
*/
/**
* @callback GridIteratee
* @param value
* @param {number} x
* @param {number} y
* @param {Grid} grid
* @param {Array} row
*/
module.exports = {
/**
* @param {Grid} grid
* @returns {Array.<Cell>}
*/
cells: lift(_.flatMap, _.map, (value, x, y) => ({ value, x, y })),
/**
* Runs a function on each cell.
* @param {Grid} grid
* @param {GridIteratee} f
* @returns {undefined}
*/
forEach: lift(_.each, _.each, (value, x, y, grid, row, f) =>
f(value, x, y, grid, row)
),
/**
* Maps values of the cells.
* @param {Grid} grid
* @param {GridIteratee} f
* @returns {Grid}
*/
map: lift(_.map, _.map, (value, x, y, grid, row, f) =>
f(value, x, y, grid, row)
),
/**
* Matrix transposition from maths. Inverts columns and rows. https://en.wikipedia.org/wiki/Transpose
* @param {Grid} grid
* @returns {Grid}
*/
transpose
};
function lift(fgrid, frow, fvalue) {
return (grid, ...args) => {
return fgrid(grid, (row, y) => {
return frow(row, (value, x) => {
return fvalue(value, x, y, grid, row, ...args);
});
});
};
}
function transpose(grid) {
return _.times(grid[0].length, x => grid.map(row => row[x]));
}