Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to circle through an array?

Tags:

javascript

I'm wondering if there is a more effective way of circling through an array. For my purposes, the array is holding image sources. When the last image is shown and the next button is pushed it circles back to the first image. If the previous button is pushed on the first image it circles to the last image.

This is what I was able to come up with, but I feel there's a more efficient way to go about it.

var marker = 0;

// Circle through an array.
function moveMarker(array, action, direction) {
    if (!direction) {
        if(marker == array.length - 1)
            marker = -1;
        marker += 1;
        action();
    }

    else {
        if (marker == 0)
            marker = array.length;
        marker -=1;
        action();
    }
}
like image 458
iamnotoriginal Avatar asked Sep 13 '25 06:09

iamnotoriginal


1 Answers

Yes, you can use the % modulo operator:

var marker = 0;

// Circle through an array.
function moveMarker(array, action, direction) {
    if (!direction) {
        marker = (marker + 1) % array.length;
    }
    else {
        marker = (marker + array.length - 1) % array.length;
    }
    action();
}

or even:

var marker = 0;

// Circle through an array.
function moveMarker(array, action, direction) {
    marker = (marker + array.length + (direction ? -1 : 1)) % array.length;
    action();
}
like image 166
Guffa Avatar answered Sep 15 '25 21:09

Guffa