mirror of
https://github.com/10h30/odin-javascript-exercises.git
synced 2026-06-05 15:09:09 +09:00
Merge branch 'master' of TOP/javascript-exercises
This commit is contained in:
+24
-3
@@ -1,5 +1,26 @@
|
||||
const caesar = function() {
|
||||
const caesar = function(string, shift) {
|
||||
return string
|
||||
.split("")
|
||||
.map(char => shiftChar(char, shift))
|
||||
.join("");
|
||||
};
|
||||
|
||||
}
|
||||
const codeSet = code => (code < 97 ? 65 : 97);
|
||||
|
||||
module.exports = caesar
|
||||
// this function is just a fancy way of doing % so that it works with negative numbers
|
||||
// see this link for details:
|
||||
// https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers
|
||||
const mod = (n, m) => (n % m + m) % m;
|
||||
|
||||
const shiftChar = (char, shift) => {
|
||||
const code = char.charCodeAt();
|
||||
|
||||
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
|
||||
return String.fromCharCode(
|
||||
mod(code + shift - codeSet(code), 26) + codeSet(code)
|
||||
);
|
||||
}
|
||||
return char;
|
||||
};
|
||||
|
||||
module.exports = caesar;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const caesar = require('./caesar')
|
||||
const caesar = require("./caesar");
|
||||
|
||||
test('works with single letters', () => {
|
||||
expect(caesar('A', 1)).toBe('B');
|
||||
|
||||
Reference in New Issue
Block a user