patternjavascriptMinor
Simplified Caesars Cipher
Viewed 0 times
caesarssimplifiedcipher
Problem
I'm studying functional programming, and I have the following problem to solve. It's an simplified version of Caesars Cipher:
I made the following implementation:
It works fine, I only want to know if there is performance issues, and what can I do to improve my code?
- 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) 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?
Solution
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:
Ah, already better.
I'm no javascript 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.
Give it some [vertical] air:
const rot13 = (str) => str
? (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 javascript 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.
Code Snippets
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)))
: '';Context
StackExchange Code Review Q#120813, answer score: 2
Revisions (0)
No revisions yet.