Math operations limited by boundaries: adding and subtracting

What is the proper way to implement this logic in JavaScript:

    Row-=21;
    if (Row < 1) {
        Row = 1;
    }

Answer №1

Here is a solution for you:

Row = Math.max( Row-21, 1);

A different approach:

If you're looking to establish a minimum and/or maximum range, consider creating your own function within the Number prototype.

Number.prototype.adjust = function( adj, min, max ) {
    if( isNaN( min ) ) min = -Infinity;
    if( isNaN( max ) ) max = Infinity;
    var res = this + ~~adj;
    return res < min ? min : res > max ? max : res;
};

You can then apply it as follows:

Row = Row.adjust( -21, 1, 50 ); /* adjustment, min, max */
  • The first parameter represents the adjustment
  • The second parameter defines the minimum range (enter null for no minimum)
  • The third parameter specifies the maximum range (enter null or leave blank for no maximum)

Answer №2

Update the Row variable by checking if it is greater than 22, then subtract 21 from Row, otherwise set Row to 1.

Answer №3

row-=21;
if (row < 1) {
    row = 1;
}

This code appears to be JavaScript that is already valid.

The only change required would be to initialize your "row" variable like so:

let row = 0;

Answer №4

Let's have some fun with a different approach by replacing the role of the operator with a function:

function createLimitedOperation( limit, type ){
  var operationFunc = function operationFunc(value, change){
    if( type === 'add' ){
       var upperLimit = limit; 
       return (value + change > upperLimit) ? upperLimit : value + change; 
    } else {
       var lowerLimit = limit;
       return (value - change < lowerLimit) ? lowerLimit : value - change;               
    }
  }  
  return operationFunc;
}

Now let's create any specific limited operator functions that you may require:

var subtractLimitedByOne = createLimitedOperation(1,'subtract');
var subtractLimitedByTen = createLimitedOperation(10,'subtract');
var addLimitedByFifty = createLimitedOperation(50,'add');

Then try them out like this:

var startingValue = 20;

subtractLimitedByOne(startingValue,12); // 8
subtractLimitedByTen(startingValue,12); // 10
addLimitedByFifty(startingValue,37); // 50

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

I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/> <input type="time" onChange={(e)=>setTime(e.target.value)} /> If the selected date is after today and the time is after the current time, display a valida ...

How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again. View the DEMO here. Challenge Description:- I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

Can JavaScript be used to upload a file directly to memory for processing before transferring it to the server?

I'm exploring the idea of using a JavaScript encryption library (not Java) to encrypt a file before sending it to the server. Is it feasible to perform this process on the client-side and then upload the encrypted file using JavaScript, storing it in ...

Comparison between using jQuery to append and execute a <script> tag versus using vanilla JavaScript

As I enhance my application, I've made the decision to embrace Bootstrap 5, which no longer relies on jQuery. Consequently, I am working to eliminate this dependency from my application entirely. One of the changes I'm making is rewriting the Ja ...

Implementing Ajax to Load Template-Part in Wordpress

Hey there! I'm currently working on enhancing my online store by adding a new feature. What I'd like to achieve is that when a customer clicks on a product, instead of being taken to the product page, the product details load using AJAX right on ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

Unable to integrate any modules or components from bit.dev into my React application

I am currently working on a React project and encountering an issue with importing a component from bit.dev. After installing the package via my terminal with the command: bit import nexxtway.react-rainbow/button You can find more information about it t ...

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3'); let letters = new Array('a','b','c'); let length = numbers.length; let str = 'abcdefgabcdefg'; for (let i=0; i<length; i++) { let regex = new ...

What causes the error of inputRef.current being null in CurrencyTextField?

When attempting to target the second 'CurrentTextField' after changing the value of the first 'CurrentTextField', an error occurs stating 'inputRef.current is null'. import React, {useRef } from 'react'; import Curr ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data. var blogData = [ { "blogTitle":"Bangladesh", "imagePath":"/img/blog/bangladesh.jpg" },{ "blogTitle":"In ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

How to capture the "chip close" event in Vuetify

Exploring the vuetify realm as a newcomer, I find myself grappling with event handling while working on my first web app project. Specifically, I am currently developing a "UserPicker" component using VAutocomplete. This component functions by sending an ...

Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface: import * as Bluebird from "bluebird"; import { Article } from '../../Domain/Article/Article'; export interface ITextParsingService { parsedArticle : Article; getText(uri : string) : B ...

The React component fails to re-render upon the initial state update

Currently, I am working on a straightforward survey that requires simple Yes or No answers. The questions are stored in a separate file called QuestionsList.js: Here is the list of questions: const QuestionsList = [ "Do you believe in ghosts?", "Have you ...