For my Angular6 App project, I am currently working on implementing Conway's Game of Life. My goal is to create a two-dimensional array of class instances with dimensions n x m. In vanillaJS, I managed to achieve this using the following code snippet:
generateInitialState(bias) {
return [...Array(this.rows)]
.map((a, i) => [...Array(this.columns)]
.map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}
This code snippet generates an Array with a length equal to this.rows, which contains Arrays filled with n (this.columns) instances of the Cell class. For example, when this.rows = this.columns = 4 (output from console):
[ [ Cell { x: 0, y: 0, state: 'alive' },
Cell { x: 1, y: 0, state: 'dead' },
Cell { x: 2, y: 0, state: 'alive' },
Cell { x: 3, y: 0, state: 'dead' } ],
[ Cell { x: 0, y: 1, state: 'alive' },
Cell { x: 1, y: 1, state: 'alive' },
Cell { x: 2, y: 1, state: 'dead' },
Cell { x: 3, y: 1, state: 'dead' } ],
[ Cell { x: 0, y: 2, state: 'alive' },
Cell { x: 1, y: 2, state: 'alive' },
Cell { x: 2, y: 2, state: 'alive' },
Cell { x: 3, y: 2, state: 'dead' } ],
[ Cell { x: 0, y: 3, state: 'dead' },
Cell { x: 1, y: 3, state: 'alive' },
Cell { x: 2, y: 3, state: 'alive' },
Cell { x: 3, y: 3, state: 'alive' } ] ]
The above logic functions correctly in vanillaJS and generates the Array as expected. However, when translating the code to TypeScript, it only returns an empty array with a length equal to this.rows. The TypeScript equivalent appears to compile down to:
function generateInitialState(bias) {
var _this = this;
return Array(this.rows).slice().map(function (a, i) { return Array(_this.columns).slice().map(function (b, j) { return new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'); }); });
}
How can I modify the TypeScript implementation to function properly?
Full Code
class Game {
constructor(columns, rows, randomBias){
this.columns = columns;
this.rows = rows;
this.randomBias = randomBias;
this.cells = this.generateInitialState(this.randomBias);
}
/* Content omitted for brevity */
generateInitialState(bias) {
return [...Array(this.rows)]
.map((a, i) => [...Array(this.columns)]
.map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}
}
class Cell{
constructor(x, y, state){
this.x = x;
this.y = y;
this.state = state;
}
}
let a = new Game(4, 4, 0.5);
console.log(a.cells);