Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How work this javascript arrow function code in tetris?

LINK

const KEY = {
    LEFT: 'ArrowLeft'
}

const moves = {
    [KEY.LEFT]: (p) => ({...p, x: p.x - 1}) // i cant understand this part
}

//on keydown event
let p = moves[KEY.LEFT](piece); // and this

piece is an instance. and after that code, It seems that the x and y of p is transferred to a piece to implement the movement

I spent hours on Google trying to figure out what grammar that was, but I ended up failing…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading