Skip to main content

Strange and inconsistent behavior during modifying an object in JavaScript in Chrome environment [duplicate]

I could not find anything remotely close to this problem anywhere else on the internet. This is simply a bizarre issue. I am making a Chess game using Typescript. I have a Validator class that holds all the states of the game including an object representation for an Chess board, which is modified after each valid move. And that's where the bug occurs. Here is the board object ->

export interface BoardType {
    [file: string]: {
        [rank: string]: string;
    };
}

export const BoardMap: BoardType = {
    a: {
        '1': '',
        '2': '',
        '3': '',
        '4': '',
        '5': '',
        '6': '',
        '7': '',
        '8': '',
    },

then 7 more files. I have a function that takes this board object and adds the pieces according to the given FEN string. That function works correctly and is not relevant here. After running that function with the default FEN the board[a]['1'] would be 'R' (white Rook), board[g]['8'] would be 'n' (black Knight) and so on. Here is the code that updates the board and where the issue is most likely occurring ->

export const updateBoardMap = (
  piece: string,
  origin: string,
  dest: string,
  boardMap: BoardType
): BoardType => {
  // getOriginAndDestInfo works correctly
  const [originFile, originRank, destFile, destRank] = getOriginAndDestInfo(
    origin,
    dest
  );

  let boardMapToUpdate: BoardType = { ...boardMap };

  // Empty the original square and place the piece on the destination square
  boardMapToUpdate[originFile][originRank] = '';
  boardMapToUpdate[destFile][destRank] = piece;

  return boardMapToUpdate;
};

This updateBoardMap function is called here ->

private NewMove(): void {
    // Update the board map
    const updatedBoardMap = helpers.updateBoardMap(
      this.movingPiece,
      this.movingPiecesOrigin,
      this.movingPiecesDest,
      this.boardMap
    );
    
    this.boardMap = { ...updatedBoardMap };
    
    // Toggle the color's turn
    this.whitesTurn = !this.whitesTurn;
}

This is only called only if the move is valid. Alright, so here is the actual issue. The function updates the board most of the time correctly, about 50% of the time, but for the rest of the cases, it adds random pieces on random squares on the board with no pattern whatsoever. For example, if I play the move 1. e4, it sometimes adds a black pawn on e6 (the original e7 pawn is still there though) or a King on d5 etc. If I reload the page and play 1. e4 again, it might put pieces on totally random squares or will not do anything odd at all and work perfectly. I will post two scrreenshots of what it looks like.

Picture of bug 1

Picture of bug 1

You will see that after the first move, it adds random pieces on random squares. This is incredibly frustrating. This happens ONLY in the browser environment (Chrome) and never on Node. And since the validity of a move depends on boardMap I might not be able to play moves that should be valid. Like,if it puts a pawn on e6, I won't be able to play 1. ..e5 even though that move would have been valid without the bug.

I have 0 idea why this occurs. This is not a very complicated operation. I know that objects are passed by references so I am using the spread operator {...} both times. I have wrote extensive tests for this function with many moves and all of them pass. This issue never occurs in Node as I mentioned earlier. I have tested it in different ways many, many times and it always works. But as soon as I am on the browser, it shows up. There is no consistency or pattern and honestly I am out of ideas to solve this. I would highly appreciate someone solving this mystery for me. Thank you.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/MqyfUEt

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...