Is it possible to decrement the index of an array by 1 and seamlessly loop back to the end in just one line of code?

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;
}

Answer №1

Give this line a shot:

function reduce() {
    position = (position - 1 + list.length) % list.length;
}

Decrease the position value by 1, then add the length of the list to convert a negative index into a positive one. Finally, apply the modulo operator to ensure the position stays within the list boundaries.

Answer №2

To achieve the same outcome as increasing, simply incorporate an additional array.length to ensure the result remains positive. For example:

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

Alternatively, using a ternary or an if statement might enhance readability, although this is subjective.

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

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

JavaScript Async Ordering

I have a specific question regarding asynchronous operations in Javascript. I am currently building a Node.js API to interact with an OrientDB database, using the Node-orient package for basic connectivity functions. Some of these functions are as follows: ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

The functionality of a JQuery post within a PHP loop is not functioning optimally

I am encountering an issue with my list.php file, which generates a list with items and a button (Erledigt!) that triggers a jQuery Post to wishdelete2.php. The problem is that the jQuery post sometimes requires multiple clicks (3x or 5x) before it process ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

Ensure the validation of multiple form fields in a single function

I've implemented code to validate a form field as you input values, changing the border color to red if invalid or green if valid: function FormValidation(){ var fn=document.getElementById("firstName").value; if(fn == ""){ document.ge ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Access to the requested URL has been restricted. Flask is unable to process the method

I have been working on creating a dynamic web service for user login. Utilizing JavaScript, jQuery, and HTML, I aim to make the login process seamless and efficient. However, I have encountered an issue where, upon entering the correct username and passwor ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

Using NicEdit for uploading to your personal server

I'm having trouble uploading images using the NicEdit WYSIWYG editor on my own server. When I click on the upload image button, it redirects me to another site where I can upload the image: imgur dot com You can find a demo of this here: However, I ...

Guide on bringing in Javascript file into your Ionic/Angular application

Within my Ionic 2 application, I have incorporated three.js along with a PLYLoader extension for three.js (accessible here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PLYLoader.js) Integrating three.js is straightforward by includi ...

Tips for avoiding the forward slash in a URL parameter

$.ajax({ url: "/api/v1/cases/annotations/" + case_id + "/" + encodeURIComponent(current_plink), When I use encodeURIComponent to escape slashes, it doesn't work as expected. The code converts the "slash" to "%2F", but Apache doesn't reco ...

Creating a dynamic link in Vue JS is a cinch!

I currently have the following code snippet: <b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100"> <b-dropdown-item @click="selectedFactory='China'"> ...

A collection of items containing a group of elements within each item

I have been working on a procedure that should return an array of objects and assign it to a property within another object. shipment.item(i).stuff = GetStuffArray() Get Stuff Array Public Function GetStuffArray() As Stuff() Dim stuff(5) As St ...

Populate your HTML with JSON data

I need some guidance on how to achieve a specific task. I have a PHP file that retrieves data from a MySQL database and returns it in JSON format. Now, I want to display this data in HTML with "data_from_json" replaced by "18.5". Any assistance would be gr ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

Securing Your Data: How to Protect and Reveal Information with Aes Encryption in C#

I am attempting to store an encrypted string as a byte array in an SQL database, but I seem to be encountering some issues. Here is the code snippet: private void loginBtn_Click(object sender, EventArgs e) { try { string ...

Utilizing jQuery for interacting with iframes

My script functions perfectly on the page, but when I embed it using an iframe, the jQuery features stop working even though the script is written as usual. Even using $.noConflict(); does not resolve the issue. ...

Is it possible to set client-certificate as optional with Node SSL (using rejectUnauthorized: true does not achieve this)?

I have been exploring how to enable two-way SSL authentication in Node.js, following up on a previous thread: Enabling 2-way (client-authenticated) SSL in node.js? Now that I have successfully implemented client-authentication/2-way SSL, the next step is ...