Imagine I am manually adjusting the index of an array in JavaScript. I have functions to increase and decrease the index, with the goal of looping back to the beginning or end of the array when reaching the limits. While the increase function can be written in a single line, is there a way to achieve the same for the decrease function?
const array = [ /* ... */ ];
let index = 0;
function increase() {
// One line - the simplicity is satisfying.
index = (index + 1) % array.length;
}
function decrease() {
// More than one line - it feels unnecessarily cumbersome.
index -= 1;
if (index < 0) {
index = array.length - 1;
}
}
Although using a ternary operator can one-line the decrease
function, some may view it as a shortcut. Personally, I find multi-lining ternaries to be more readable.
function decrease() {
index = (
index < 1
? array.length
: index
) - 1;
}