3
\$\begingroup\$

I'm studying functional programming, and I have the following problem to solve. It's an simplified version of Caesars Cipher:

  • You need to write a function, which will take string encoded with Caesar cipher as a parameter and decode it.
  • The one used here is ROT13 where the value of the letter is shifted by 13 places. e.g. 'A' ↔ 'N', 'T' ↔ 'G'.
  • You have to shift it back 13 positions, such that 'N' ↔ 'A'.

I made the following implementation:

const head = (str) => str[0];
const tail = (str) => str.slice(1);
const code = (str) => str.charCodeAt(0);

const rot13 = (str) => str ? (code(str) < 65 || code(str) > 90) ? head(str).concat(rot13(tail(str))) : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str))) : '';

It works fine, I only want to know if there is performance issues, and what can I do to improve my code?

\$\endgroup\$
2
\$\begingroup\$

I don't know about the performance, but readability-wise, cramming that double-nested ternary on a single line of code isn't, well, ideal.

Give it some [vertical] air:

const rot13 = (str) => str 
   ? (code(str) < 65 || code(str) > 90) 
       ? head(str).concat(rot13(tail(str))) 
       : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str))) 
   : '';

Ah, already better.

I'm no expert, but being all inline, it probably performs better than if you further improved readability by introducing a function for each of the two outcomes of the inner condition... on the other hand, that could just as well be premature optimization - so I'd still go for readability and extract the logic into its own function.

\$\endgroup\$
  • \$\begingroup\$ I agree that my code is not that readable. I solved a little of it by splitting the functions (imagine each code(str) as str.charCodeAt(0)), but as Ecmascript does not have pattern matching, there's no much to do. Thanks. \$\endgroup\$ – Mateus Felipe Feb 22 '16 at 20:42
  • \$\begingroup\$ @I'lladdcommentstomorrow The functionality is in it's own function itself. I only made a sweet syntax of it, but the problem-solving logic is all in one function. \$\endgroup\$ – Mateus Felipe Feb 22 '16 at 20:50
  • \$\begingroup\$ @Mat'sMug About your edit, have a look at ES6 arrow function, this will answer your question. The function is there, even with no function keyword being used. \$\endgroup\$ – Mateus Felipe Feb 22 '16 at 20:51
  • \$\begingroup\$ I'll vote your question until someone gives an answer with more info. \$\endgroup\$ – Mateus Felipe Feb 22 '16 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.