Add solution directories for exercises

This commit is contained in:
thatblindgeye
2022-02-20 14:07:44 -05:00
parent 1971712fde
commit fb1a2db8d7
26 changed files with 600 additions and 0 deletions
+26
View File
@@ -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!');
});