javascripttetris

How work this javascript arrow function and destructuring assignment code in tetris?


class Piece {

    constructor() {
        this.x = 0;
        this.y = 0;
    }

    move(p) {
        this.x = p.x;
        this.y = p.y;
    }
}

let piece = new Piece();

const KEY = {
    LEFT: 'ArrowLeft'
}

const moves = {
    [KEY.LEFT]: (p) => ({...p, x: p.x - 1})
}

document.addEventListener('keydown', event => {
    if (moves[event.key]) {  
        event.preventDefault();
    
        let p = moves[event.key](piece);
    
        piece.move(p);
        }
    }
});

I cannot understand how to move a piece. piece is an instance of class Piece, to the best of my knowledge.

When variable p is declared, moves[event.keyCode](piece) is included, I don't know how this grammar works.

Especially this part.[KEY.LEFT]: (p) => ({...p, x: p.x - 1})

I'm wondering why there should be a : between [KEY.LEFT] and (p), and if there's no parentheses over the arrow function, the interpreter gets a grammar error. this. '('{...p, x: p.x - 1}')'

and ...p, x: p.x - 1 And what this means. I'm sorry it's such a basic grammar, but I don't know where I can ask questions.

I think I've tried something too difficult that doesn't fit my level..


Solution

  • moves[KEY.LEFT] is a reference to a function. This function accepts p as an argument. You are passing piece to this function.

    Within the function it applies the Spread operator to define a new object which is effectively a clone of the piece which was passed in, with the x property ameneded.

    Here's an example of your original code using more readable syntax, which may make its logic clearer:

    const moves = {
      'ArrowLeft': function(piece) {
        return {
          ...piece,
          x: piece.x - 1
        }
      }
    }