Hello reference.

Switching daily from C++ (day work) to JS (hobby project) results in happily careless programming. I’m so thrilled with duck typing, that in some functions it’s seems to be obvious, that passed object argument is a reference and yet, when I’m writing function using a reference only to check something, sometimes I’m forgetting that I’m performing an operation on a “living being”:

TilesManager.prototype.getAdjacent = function(gamePos, direction) {
	switch (direction) {
		case MovementDirections.U:
			gamePos[1]--;
			break;
		case MovementDirections.R:
			gamePos[0]++;
			break;
		case MovementDirections.D:
			gamePos[1]++;
			break;
		case MovementDirections.L:
			gamePos[0]--;
			break;
	}
	return this.get(gamePos[0], gamePos[1]);
}

gamePos modified outside. A moment ago function was receiving two numbers (not objects) posX, posY and everything was a-ok (pass by value).

Ok, “let’s make gamePos uppercase (ergo suggest DON’T F TOUCH THIS), make a copy at the beginning and use it instead:

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = GAME_POS;
	switch (direction) {
		case MovementDirections.U:
			gamePos[1]--;
			break;

No. Still having a reference: the gamePos IS the GAME_POS. So let’s make a copy. Stackoverflow to the rescue.

As a js beginner I’m surprised: there is no ‘proper’ way to clone objects. Conclusion from the Stack (I’ve packed solution into a function):

function cloneProperties(TO_CLONE) {
	return JSON.parse(JSON.stringify(TO_CLONE));
}

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = cloneProperties(GAME_POS);

Only properties copied, no functions. Will do. Phew. Valuable lesson.