Categories
Coding Exercises

Rotational Cipher Solution – Meta Careers Coding Exercise

Following is my solution to Meta’s Coding Exercise: Rotation Cipher.

function rotationalCipher(input, rotationFactor) {
	let str = input.split("");
	const a_code = "a".charCodeAt(0),
		z_code = "z".charCodeAt(0),
		A_code = "A".charCodeAt(0),
		Z_code = "Z".charCodeAt(0),
		zero_code = "0".charCodeAt(0),
		nine_code = "9".charCodeAt(0);
	for (let i = 0; i < str.length; i++) {
		const char = str[i];
		const code = char.charCodeAt(0);
		if (
			(a_code <= code && code <= z_code) ||
			(A_code <= code && code <= Z_code) ||
			(zero_code <= code && code <= nine_code)
		) {
			let newCode;
			if (isNaN(char)) {
				if (char === char.toLowerCase()) {
					// Rotate lower case letters
					newCode = code - a_code + rotationFactor;
					newCode %= 26;
					newCode += a_code;
				} else {
					// Rotate upper case letters
					newCode = code - A_code + rotationFactor;
					newCode %= 26;
					newCode += A_code;
				}
			} else {
				// Rotate numbers
				newCode = code - zero_code + rotationFactor;
				newCode %= 10;
				newCode += zero_code;
			}
			str[i] = String.fromCharCode(newCode);
		}
	}
	return str.join("");
}