I am attempting to solve what should be a relatively easy practice problem in JavaScript. The object is to create a function called shiftLetters() that does the following:
- Converts a string passed as a parameter to a string array comprised of the single letters within the string.
- Use the
Array.prototype.map()method to iterate over each single character in the array. - If the character is a space, it should not be transformed.
- If the character is alphanumeric, it should be transformed using
String.charCodeAt()by advancing one character forward (e.g., F becomes G, f becomes g). - Using
String.fromCharCode(), assemble a string such that, for example, 'I cannot tell a lie' is transformed to 'J dboopu ufmm b mjf.'
Here is my code so far:
var shiftLetters = function(string){
// 1. Convert string to an array of characters.
const stringArray = string.split('');
const mappedString = stringArray.map( (char) => {
for (char in mappedString) {
// TO BE DONE
}
});
}
const example = 'Able was I ere I saw Elba.';
I see the following problems with the above code and I am not sure how to resolve them:
- Though the string—in this sample, 'Able was I ere I saw Elba.'—is transformed successfully into an array comprised of single characters, e.g.
['A', 'b', 'l', 'e'...],String.prototype.charCodeAt()andString.fromCharCode()are not methods exposed by arrays and cannot be used in that context. - In searches on MDN and other online resources, I have been unable to uncover any available methods that can reference an index within an array and get the ASCII character code for that element.
Though I can see that if I did successfully create a transformed array of characters, it would then be a simple matter to employ ```Array.prototype.join()`` to create a string transformed in the way described above. I just haven't been able to figure out how to get to that point.
I would appreciate any insights that can be offered. In the meantime, I will continue my research. If I find the answer, I will post it here.
Thanks in advance for your help.
Sincerely,
Robert Hieger