Hi I came acroos this challenge from jschallenger page. I write the following code and It's working Fine unless any capital letter is passed. It seems to me ltr = "abcdefghijklmnopqrstuvwxyz" is not the right way. Could you please tell how can I improve my code?
function myf(a){
let ltr = "abcdefghijklmnopqrstuvwxyz"
let newstr =""
for(i=0; i<=a.split("").length-1; i++){
let str = ltr.indexOf(a.charAt(i))+1
let mystr = ltr.charAt(str )
newstr += mystr
}
console.log(newstr)
}
myf("bnchm") // result: coding
myf("bgddrd") // result: cheese
myf("sdrshmf")// result:testing
You could calculate the letter by parsing a character, get the value in a 36 numbers system and add one. To ge the wanted value without carry take the rest of 36 and if zero add ten to get an 'a' (this was a 'z' before).
function convert(string) {
let result = '';
for (const c of string) {
result += (((parseInt(c, 36) + 1) % 36) || 10).toString(36);
}
return result;
}
console.log(convert("bnchmf")); // coding
console.log(convert("bgddrd")); // cheese
console.log(convert("sdrshmf")); // testing
console.log(convert("abcdefghijklmnopqrstuvwxyz")); // bcdefghijklmnopqrstuvwxyza
Hope this code will help you.
const convert = (str) => {
let result = "";
for (const char of str) {
result += String.fromCharCode(
char.charCodeAt(0) + 1 === 123
? 97
: char.charCodeAt(0) + 1 === 91
? 65
: char.charCodeAt(0) + 1
);
}
console.log(result);
};
convert("XYZ");
convert("bgddrz");
convert("bnchmf");
// remember capitals
var obj={};
for(let itr=0;itr<arg.toString().length;itr++){
if(arg[itr]==arg[itr].toUpperCase()){
obj[itr]=true // isUpperCase
}
// toLowerCase
for(let iter=0;iter<String(arg).toLowerCase().split('');iter++){
// your code
}
The remembered capitals are used to restore uppercase letters before logging the result.