Alter caesar solution with clean code practices (#302)

This commit is contained in:
c-auri 2023-03-18 23:32:20 +01:00 committed by GitHub
parent c4301bbd9c
commit 77c5d64b37
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 10 deletions

View File

@ -1,24 +1,27 @@
const caesar = function(string, shift) { const caesar = function(string, shiftValue) {
return string return string
.split("") .split("")
.map(char => shiftChar(char, shift)) .map(char => shift(char, shiftValue))
.join(""); .join("");
}; };
const codeSet = code => (code < 97 ? 65 : 97); const isLetter = code => {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
// this function is just a fancy way of doing % so that it works with negative numbers // This function implements a version of the modulo operator
// see this link for details: // that returns the smallest positive remainder even for negative inputs.
// See this link for details:
// https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers // https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers
const mod = (n, m) => (n % m + m) % m; const mod = (n, m) => (n % m + m) % m;
const shiftChar = (char, shift) => { const shift = (char, shiftValue) => {
const code = char.charCodeAt(); const code = char.charCodeAt();
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { if (isLetter(code)) {
return String.fromCharCode( const base = code < 97 ? 65 : 97;
mod(code + shift - codeSet(code), 26) + codeSet(code) const shiftedCode = mod(code + shiftValue - base, 26) + base;
); return String.fromCharCode(shiftedCode);
} }
return char; return char;
}; };