Hello, while writing with JavaScript, I encountered the following shiftRight() function. The final section clears the last character with a dash. This is because it is overwritten. I am not understanding why this is needed, I tried to research but my efforts were unpromising. Thanks!
// === Shift all characters one space to the right (after insertion) ===
function shiftRight(row, col) {
// Flattened index of the insertion point
// Shift everything from this point to the right by 1
for (let i = ROWS * COLS - 2; i >= row * COLS + col; i--) {
const from = i; // Current character index
const to = i + 1; // Destination index (1 cell to the right)
// Convert 1D index to 2D row and column
const fr = Math.floor(from / COLS); // From row
const fc = from % COLS; // From col
const tr = Math.floor(to / COLS); // To row
const tc = to % COLS; // To col
// Move character to the right
grid[tr][tc] = grid[fr][fc];
}
// Clear the last cell in the grid
const lastIndex = ROWS * COLS - 1; // Final 1D index of the grid
const lastR = Math.floor(lastIndex / COLS); // Last row
const lastC = lastIndex % COLS; // Last col
grid[lastR][lastC] = DASH;
}
Top comments (0)