patternjavascriptMinor
Conway's Game of Life - Conventional JavaScript?
Viewed 0 times
conventionaljavascriptconwaygamelife
Problem
I'm using the Game of Life Kata to help me learn JavaScript. I've picked up the syntax through Codecademy tutorials, but my current skill level is Novice.
The example code has working functionality for initialising a
All suggestions for improvement are welcome. I'd especially like feedback on the following:
The example code has working functionality for initialising a
World with live cells and asking it to 'tick'.All suggestions for improvement are welcome. I'd especially like feedback on the following:
- JavaScript idioms and conventions
- Function and variable scoping
- Making use of built-in functions and datatypes
myapp = {};
/**
* World represents a 2 dimensional square matrix of cells.
* @param dimension
* @param liveCellCoordinates
* @returns {myapp.World}
*/
myapp.World = function(dimension, liveCellCoordinatesArray) {
this.dimension = dimension;
this.liveCellCoordinates = liveCellCoordinatesArray;
};
/**
*
* @returns {Array} of live cells after tick.
*/
myapp.World.prototype.tick = function() {
var nextGenerationOfLiveCells = [];
// for each cell in world
for(var y=0; y>> liveNeighbours of ", x, y, ": ", liveNeighbours);
return liveNeighbours;
};
myapp.World.prototype.isCellAlive = function(x, y) {
for(var cell in this.liveCellCoordinates) {
if(x === this.liveCellCoordinates[cell][0] && y === this.liveCellCoordinates[cell][1]) {
return true;
}
}
return false;
};
function isBorn(liveNeighbours) {
return liveNeighbours === 3;
}
function isSurvivor(liveNeighbours) {
return liveNeighbours === 2 || liveNeighbours === 3;
}Solution
Looks quite good overall; not much to criticise. (I'm not looking at the overall structure or logic - just the style; the game of life can be written in so many ways)
Anyway, what I have is very trivial:
Anyway, what I have is very trivial:
- Missing indentation in the bodies of
tickandgetLiveNeighbourCount
- Don't use a
for...inloop for arrays (inisCellAlive); better and clearer to use a regularfor-loop like you do elsewhere.
- You ought to define
myappaswindow.myapp. Right now it's implicitly global, because it's missing avardeclaration, but you might as well make that explicit (or perhaps it doesn't need to be global at all?)
- Some more comments in the code itself would probably be nice.
Context
StackExchange Code Review Q#44240, answer score: 5
Revisions (0)
No revisions yet.