Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140071

How can I store the previous value of a variable in Javascript?

$
0
0

In a project of mine, I have a snippet of some "buggy" code. Function makeMove updates the global variable board and function takeMove resets the board. While the board is changed I push the board value into an array and then reset the board. The problem is that when I access this array, the board values stored inside of it are the values of the reset board when I want the values of the updated board within the array.

I tried shallow copying the updated board and then storing it but that does not work, I am not deep copying the array since I will be using this code for thousands of iterations, and deep copying can take up a lot of performance.

Here is the snippet of code:

let board = [
    ["C", "H", "B", "Q", "K", "B", "H", "C"],
    ["P", "P", "P", "P", "P", "P", "P", "P"],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["", "", "", "", "", "", "", ""],
    ["p", "p", "p", "p", "p", "p", "p", "p"],
    ["c", "h", "b", "q", "k", "b", "h", "c"]
];

function makeMove(from, to) {
    let piece = board[from.y][from.x];
    board[from.y][from.x] = "";
    pieceBeforeOnToSQ = board[to.y][to.x];
    board[to.y][to.x] = piece;
}

function takeMove(from, to) {
    let piece = board[to.y][to.x];
    board[to.y][to.x] = pieceBeforeOnToSQ;
    board[from.y][from.x] = piece;
}

makeMove(position, {
    x: index % 8,
    y: Math.floor(index / 8)
});
pseudoLegalNodeList.push(board);
takeMove(position, {
    x: index % 8,
    y: Math.floor(index / 8)
});

Note: The variable pieceBeforeOnToSQ is global.

If you need any clarifications about the question or code, feel free to ask.


Viewing all articles
Browse latest Browse all 140071

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>