2023-03-18 22:32:20 +00:00
|
|
|
const caesar = function(string, shiftValue) {
|
2021-04-30 10:12:52 +00:00
|
|
|
return string
|
|
|
|
.split("")
|
2023-03-18 22:32:20 +00:00
|
|
|
.map(char => shift(char, shiftValue))
|
2021-04-30 10:12:52 +00:00
|
|
|
.join("");
|
|
|
|
};
|
2017-08-25 18:59:26 +00:00
|
|
|
|
2023-03-18 22:32:20 +00:00
|
|
|
const isLetter = code => {
|
|
|
|
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
|
|
|
}
|
2017-08-25 18:59:26 +00:00
|
|
|
|
2023-03-18 22:32:20 +00:00
|
|
|
// This function implements a version of the modulo operator
|
|
|
|
// that returns the smallest positive remainder even for negative inputs.
|
|
|
|
// See this link for details:
|
2021-04-30 10:12:52 +00:00
|
|
|
// https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers
|
|
|
|
const mod = (n, m) => (n % m + m) % m;
|
|
|
|
|
2023-03-18 22:32:20 +00:00
|
|
|
const shift = (char, shiftValue) => {
|
2021-04-30 10:12:52 +00:00
|
|
|
const code = char.charCodeAt();
|
|
|
|
|
2023-03-18 22:32:20 +00:00
|
|
|
if (isLetter(code)) {
|
|
|
|
const base = code < 97 ? 65 : 97;
|
|
|
|
const shiftedCode = mod(code + shiftValue - base, 26) + base;
|
|
|
|
return String.fromCharCode(shiftedCode);
|
2021-04-30 10:12:52 +00:00
|
|
|
}
|
|
|
|
return char;
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = caesar;
|