Home > front end >  Increase and reduce index withing a fixed circular range in JS
Increase and reduce index withing a fixed circular range in JS

Time:02-12

I have a circular range of ascii values of a-z, from 97 to 122.
I am having trouble with decreasing the value, suppose the current value is 100 and i want to reduce it by 4 and it should return 122.

const startIndex=97
const endIndex=122

let increaseBy=reduceBy=5
let currentIndex=122
// increment 
// this works
currentIndex=startIndex ((currentIndex-startIndex increaseBy)&)

// decrement
// need help
currentIndex=attempted_something_that_you_will_find_it_as_dumb

CodePudding user response:

Modulo will walk your modulo-class as you wish, if you just keep adding your

startIndex (currentIndex&)

Now, you just make sure, your currentIndex want go below 0

you modify only the currentIndex

let startIndex = 97;
let currentIndex = 0;

for(let inc = 0; inc < 10; inc  ) {
   currentIndex  = 5;
   console.log(startIndex   (currentIndex&));
}

for(let inc = 0; inc < 10; inc  ) {
   currentIndex -= 5;
   console.log(startIndex   (currentIndex&));
}

console.log("index will go below zero -> will break");
for(let inc = 0; inc < 10; inc  ) {
   currentIndex -= 5;
   console.log(startIndex   (currentIndex&));
}

console.log("index will stop at zero -> will not break");
for(let inc = 0; inc < 10; inc  ) {
   currentIndex = Math.max(0, currentIndex - 5);
   console.log(startIndex   (currentIndex&));
}

console.log("index will reset to modulo at zero -> will not break");
for(let inc = 0; inc < 10; inc  ) {
   currentIndex -= 5;
   currentIndex = (currentIndex < 0) ? (26   currentIndex) : currentIndex;
   console.log(startIndex   (currentIndex&));
}

CodePudding user response:

The solution @thst gave works well. In short I'll mention my usage of the code

const startIndex = 97;
const endIndex = 122;
let increaseBy = (reduceBy = 5);
let currentIndex = 122;

// increment
currentIndex = startIndex   ((currentIndex - startIndex   increaseBy) % 26);
// decrement
const milansConst=7;
currentIndex = startIndex   ((currentIndex - reduceBy   milansConst) % 26);

milansConst is a mysterious number (there is no logic to it) my friend came up with to get the decrement expression he made work.

  • Related