I need to increment a string from.. let\'s say aaa
to zzz
and write every incrementation in the console (is incrementation even a word?). It would go s
This will function will do the part of incrementing the string to next sequence
function increment(str){
var arr = str.split("");
var c;
for(var i=arr.length-1; i>=0; i--){
c = (arr[i].charCodeAt(0)+1)%123;
arr[i] = String.fromCharCode(c==0?97:c);
if(c!=0)break;
}
return arr.join("");
}
I was working on another solution to increment by any number and also in reverse direction. The code still has some bugs, but just putting it up here to receive some suggestions. pass in negative numbers to go in reverse direction. Code fails for some edge cases, for eg: when character is 'a' and num is negative number
function jumpTo(str,num){
var arr = str.split("");
var c;
for(var i=arr.length-1; i>=0; i--){
c = (arr[i].charCodeAt(0)+1)%123;
c += c==0?97+num-1:num-1;
arr[i] = String.fromCharCode(c==0?97:c);
if(c!=0)break;
}
return arr.join("");
}