I try to learn Javascript by reading a lot of online tutorials, and practice working on problems on coderbit. I'm having trouble calling CaesarCipher. The function should take a string and an offset parameter, and then return a string with each alpha character shifted using any offset (leaving any characters without alpha unchanged). I have my shiftChar () function, which will take char and offset and apply the shift only for alpha characters and return a new character. Now that this is complete, I thought I could just take the original string, split it into an array, and then map this array of characters to the new array using my shiftChar () function. However, I cannot make it work, and I cannot understand why.
Is there something that I am missing in the map method? I understand that the map method automatically passes each element to an array, which it is called as the first argument. Then I just pass the offset value as an extra argument. Can someone shed some light on why this is not working and suggest a more effective approach?
var str = 'Caesar Cipher'; function CaesarCipher(str, offset){ var charArray = str.split(''); var result = charArray.map( shiftChar( char, offset )).join(''); function shiftChar(char, offset){ var isAlpha = /[Az]/; if(isAlpha.test(char)){ char = String.fromCharCode(char.charCodeAt(0) + offset); if(char > 'Z' && char < 'a' || char > 'z') char = String.fromCharCode(char.charCodeAt(0) - 26); } return char; } return result; } console.log(CaesarCipher( str, 2));
javascript arrays
tbutman
source share