is it possible to shorten these three for loops into one the code works absolutely fine, I just want to know if there is a possibility to shorten these three for loops into one for exercising reasons and also for code-readability
let board_coord = []
for (let i = 0; i < 3; i++) {
board_coord.push({
x: i * 166,
y: 0
})
}
for (let j = 0; j < 3; j++) {
board_coord.push({
x: j * 166,
y: 166
})
}
for (let k = 0; k < 3; k++) {
board_coord.push({
x: k * 166,
y: 332
})
}
console.log(board_coord)
If you mean a single top level loop, you could use a nested loop:
const SIZE = 166;
let boardCoord = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
boardCoord.push({ x: SIZE * j, y: SIZE * i });
}
}
I don't think a single loop overall would be any more readable than this.
A single loop would require a little math. (see: Remainder (%) and Math.floor())
const boardCoord = [];
for (let i = 0; i < 9; i++) {
boardCoord.push({
x: (i % 3) * 166,
y: Math.floor(i / 3) * 166
})
}
console.log(boardCoord)
Or generalized...
const WIDTH = 3;
const HEIGHT = 3;
const SCALE = 166;
const boardCoord = [];
for (let i = 0; i < WIDTH * HEIGHT; i++) {
boardCoord.push({
x: (i % WIDTH) * SCALE,
y: Math.floor(i / WIDTH) * SCALE
})
}
console.log(boardCoord)
But it's not necessarily more readable than a nested loop which can also be generalized.
const COLS = 3;
const ROWS = 3;
const SCALE = 166;
const boardCoord = [];
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
boardCoord.push({ x: SCALE * col, y: SCALE * row });
}
}
console.log(boardCoord)