Moving back and forth within a range

One simple yet commonly encountered task involves looping through a range forwards and backwards:

var currentIndex = 0;
var range = ['a', 'b', 'c', 'd', 'e', 'f'];

function getNextItem(direction) {
    currentIndex += direction;
    if (currentIndex >= range.length) { currentIndex = 0; }
    if (currentIndex < 0) { currentIndex = range.length-1; }

    return range[currentIndex];
}        
// get next "right" item
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));

The code snippet above functions efficiently, although I spent close to an hour attempting to eliminate the duplicate if check.

Is there a way to solve this issue without using an if statement? Perhaps in a more concise one-liner approach?

Answer №1

To simplify the two if statements into one unconditional statement, you can incorporate the length of the range array by adding it to the current index and then using modulo:

var currentIndex = 0;
var range = ['a','b','c','d','e','f'];

function getNextItem(direction) {
    currentIndex = (currentIndex + direction + range.length) % range.length;
    return range[currentIndex];
}

// get next "right" item
console.log(getNextItem(1));
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));
console.log(getNextItem(-1));
console.log(getNextItem(-1));

console.log(getNextItem(4));
console.log(getNextItem(1));
console.log(getNextItem(1));
console.log(getNextItem(1));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Issue with Framework7: Swiper slider link not functional

On one of the slides in my swiper slider, there is a link that redirects to a file named year.html Here is the link: <a href="year.html">Add by year, make & model</a> Source code for swiper slider: http://pastebin.com/ggN3TqgA Content ...

"Adjusting the width of columns in a Datatable

I have arranged a data table with multiple rows and columns, and I am seeking guidance on how to increase the width of the "Tel. 1, Tel. 2, and Fecha" columns to ensure that the text appears on a single line. I've attempted adjusting the s width and t ...

Understanding the status of HTTP requests or observing the updates of observables in Angular2/Typescript is essential

I've been working on an Angular2 and Typescript application where I'm utilizing Angular2's HTTP methods to retrieve data from a database within a service. The service is triggered inside a component's onInit() function and I'm able ...

Combine loop results into a string using jQuery

When using jQuery, I need to append a multiline string to an element by adding a string return from each value in a for loop. $("songs-table-tr").append('tr id="songs-table-tr'+count+'" style="display: none">\ ...

Is there a substitute for the bind function?

While delving into Functional programming and optimizing V8 code, I became curious about the optimizability of the bind function by V8. Upon inspecting the native JavaScript code, I stumbled upon these lines: var newfn = function() { // Combine the s ...

Is there a way to determine if a submit button has been clicked in order to prevent my function from executing?

I'm currently developing a platform for uploading images. Once a user uploads an image successfully, it gets saved in 4 different sizes within separate folders. They are then redirected to the same page with new content, where they can proceed to crop ...

Exploring the crossroads of MongoDB, Mongoose, and Node.js: An in-depth look

Searching for ways to retrieve references in MongoDB using Node.js and Mongoose. After reading the documentation, I discovered that there are two options available: Manual References or DBRefs. Given that Manual References are recommended, I proceeded to ...

Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

In what way can I ensure that the value of currentIndex is consistently set to 0 before each calculation?

Is there a way to set the Value of currentIndex to always be 0? The calculation of (CRANK1 + CRANK2) + (DRANK1 + DRANK2) should result in (0 + selected amount), but it is currently calculating as (selected amount + selected amount). Any assistance would ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Applying a transparent layer to all slider images, with the exception of the one that is

I am utilizing an IosSlider that is functioning properly, but I am looking to enhance it by adding opacity to all images except for the selected image. This adjustment will make the selected image stand out more and enable users to focus on one image at a ...

Error message: "Missing attribute X in the GraphQL result for Vue"

Recently started using vue as a frontend with vue 2.3.11 and Django 3 as the backend, connecting them through Apollo via vue-cli. In my backend, I have a table named documents which consists of only a name and an id field. I am fetching this data from the ...

Learn how to implement JavaScript code that allows a video to start playing only upon clicking a specific button

Within the confines of a div lies a <video autoplay> <source src='myvid'> </video>. This div initially has a display ='none' setting in its CSS. Upon receiving a click event, the display property changes from none to b ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

EJS variable not detected by Visual Studio IDE in JavaScript file

Working on a Node.js project with the express framework and utilizing EJS as the template engine, my IDE of choice is Visual Studio. Encountering an issue when using EJS variables within the same ejs file. Though it renders correctly and functions perfect ...

Tips for adding an array to an input field by enclosing each value within a span element

I am working on a project that involves checkboxes. Every time I check or uncheck a checkbox, I want its value to be added to a search box with each value enclosed in a span tag. Here is my current progress: At the moment, I am simply updating the input ...

Simple steps for capturing the JSON reply containing multiple arrays on an Android device

This is my JSON data format [{"member":[{"id":"1","name":"A V S Murthy (Sanjeev)","mobile1":"9845072215","mail_id":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caaba6aba7baaba6a6a3e4a7bfb8bea2b38aada7aba3a6e4a9a5a7">[e ...

Check the value of a single bit in JavaScript: Is the bit on (1) or off (0)?

Is there a way in JavaScript to determine if a single Bit is On (1) or Off (0)? function isBitOn(number, index) { // ... ? } // Example: let num = 13; // 1101 isBitOn(num, 0); // true 1 isBitOn(num, 1); // false 0 isBitOn(num, 2); // true 1 isBit ...