skip to Main Content

Lets say that I’m manually adjusting the index of an array in JavaScript. I have a function that will increase the index and another that will decrease it. I want these functions to loop (so increasing the index when already at the end will reset the index to 0 and decreasing when the index is at 0 will reset the index to the array length – 1).

I can create the increase function in a single line. Is there a way to write the decrease function in a single line as well?

const array = [ /* ... */ ];
let index = 0;

function increase() {
    // One line - this makes me happy for some reason.
    index = (index + 1) % array.length;
}

function decrease() {
    // More than one line - this makes me irrationally sad.
    index -= 1;
    if (index < 0) {
        index = array.length - 1;
    }
}

I know it’s possible to one-line the decrease function by using a ternary, but I feel like that’s a bit of a cheat (I also find that multi-lining ternaries makes them much easier to read).

function decrease() {
    index = (
        index < 1
        ? array.length
        : index
    ) - 1;
}

2

Answers


  1. You can do the same you did for increasing and just add an extra array.length to keep the result positive, i.e.:

    index = (index - 1 + array.length) % array.length;
    

    I’d think a ternary or an if would be more readable though, but that’s just my personal opinion.

    Login or Signup to reply.
  2. You may try this line :

    function decrease() {
        index = (index - 1 + array.length) % array.length;
    }
    

    You decrease the index by 1, and add the length of the array to transform a negative index in a positive one. Then you apply your modulo to stay in the boundaries of the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search