Open simon-tiger opened 5 years ago
In the very beginning, you tried to use higher-order functions:
grid = new Array(4);
grid.fill().map(x => [0, 0, 0, 0]);
However, there was a very simple mistake. map()
returns a new array!
grid = new Array(4);
grid = grid.fill().map(x => [0, 0, 0, 0]);
or more concisely:
grid = new Array(4).fill().map(x => [0, 0, 0, 0]);
However, fill()
takes an argument which is what to fill the array with! So you could have even said:
grid = new Array(4).fill([0, 0, 0, 0]);
Also, for any JS constructor call, the new
is optional! So you could have even said:
grid = Array(4).fill([0, 0, 0, 0]);
Lastly, [0, 0, 0, 0]
could also be written this way! (except, this actually only makes it longer, not more concise):
grid = Array(4).fill(Array(4).fill(0));
However, you didn't notice any of that, and in the end just hardcoded it! So can you add that back in?
There's one problem with the following:
grid = Array(4).fill([0, 0, 0, 0]);
grid = Array(4).fill(Array(4).fill(0));
The argument for fill doesn't get evaluated at each position in the array; just once. This means that each item in
grid
is pointing to the same array which would cause unexpected behavior.
OK, we already have 4 parts of the 2048 challenge, but they did not code the following: