Tuesday, October 4, 2016

Javascript's fromCharCode() method

So as I mentioned in my previous post I've been making my way through freecodecamp.com's curriculum during my downtime. While working through the intro bonfires I stumbled upon something mildly interesting:

Caesar's Cipher solution

The above is my solution for the "Caesar's Cipher" bonfire which asks you to translate a string by substituting each letter for the one 13 places in the alphabet from the input string (e.g. B = O). Since I've played around in C I'm familiar with ASCII character codes so the idea behind this particular algorithm wasn't that challenging. What was challenging was getting it to work correctly.

The first part of this code converts each letter of the input string into it's corresponding ASCII code character and then pushes it to an array after modifying it to fit the requirements of the algorithm; values A-M were char value + 13, while values A-Z were char value - 13, and any other character was left unchanged. Nothing earth shattering at this point.

From here the only trick was to convert these character codes back to their corresponding values. Javascript has a built in method, String.fromCharCode(), that does just this, though it's a bit trickier then I realized...

Javascript, just like every other programming language I've encountered, allows you to reference a variable when assigning a new value to that same variable (e.g. x = x + 5;), in fact, like most languages it actually has a host of built in shorthand operators to make it easier to do so: +=, -=, *=, /=, etc...

That's all well and good. The strange this was that this wasn't an option when using the String.fromCharCode() method. This method was new to me as I'm not used to dealing with many of the static methods in Javascript (It's the first time I've actually used the "String" object (prototype?)) in JS so maybe that explains my difficulties in getting this to work...

I spent ten minutes trying to get my second for loop to run with the code

arr[j] = String.fromCharCode(arr[j]);

and the code not working. Finally I decided to push the converted values to a new array (storArr) in the code and it worked. The thing is, I don't know why this worked for the new array and not for the previous one :(.


No comments:

Post a Comment