How can a counter variable be restricted to only positive integer range?

Issue

I’m wondering how can I restrict a counter from going into the negative integer range.

var i=0;
const plus = function(){
    i += 1;
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
    i -= 1;
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
    i = 0;
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})

Solution

You can check if the result is negative and replace negative values with 0. This logic can be implemented using Math.max:

var i=0;
const plus = function(){
    i += 1;
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
    i = Math.max(i - 1, 0);
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
    i = 0;
    document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})

setTimeout(() => {
  plus();
  console.log('plus()');
}, 500);
setTimeout(() => {
  minus();
  console.log('minus()');
}, 1000);
setTimeout(() => {
  minus();
  console.log('minus()');
}, 1500);
setTimeout(() => {
  minus();
  console.log('minus()');
}, 2000);
setTimeout(() => {
  plus();
  console.log('plus()');
}, 2500);
<span id="demo"></span>

Answered By – jabaa

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.