mirror of
https://github.com/10h30/odin-javascript-exercises.git
synced 2026-06-05 15:09:09 +09:00
Add solution directories for exercises
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
const caesar = function (string, shift) {
|
||||
return string
|
||||
.split('')
|
||||
.map((char) => shiftChar(char, shift))
|
||||
.join('');
|
||||
};
|
||||
|
||||
const codeSet = (code) => (code < 97 ? 65 : 97);
|
||||
|
||||
// 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;
|
||||
@@ -0,0 +1,23 @@
|
||||
const caesar = require('./caesar-solution');
|
||||
|
||||
test('works with single letters', () => {
|
||||
expect(caesar('A', 1)).toBe('B');
|
||||
});
|
||||
test.skip('works with words', () => {
|
||||
expect(caesar('Aaa', 1)).toBe('Bbb');
|
||||
});
|
||||
test.skip('works with phrases', () => {
|
||||
expect(caesar('Hello, World!', 5)).toBe('Mjqqt, Btwqi!');
|
||||
});
|
||||
test.skip('works with negative shift', () => {
|
||||
expect(caesar('Mjqqt, Btwqi!', -5)).toBe('Hello, World!');
|
||||
});
|
||||
test.skip('wraps', () => {
|
||||
expect(caesar('Z', 1)).toBe('A');
|
||||
});
|
||||
test.skip('works with large shift factors', () => {
|
||||
expect(caesar('Hello, World!', 75)).toBe('Ebiil, Tloia!');
|
||||
});
|
||||
test.skip('works with large negative shift factors', () => {
|
||||
expect(caesar('Hello, World!', -29)).toBe('Ebiil, Tloia!');
|
||||
});
|
||||
Reference in New Issue
Block a user