diff --git a/src/core/operations/VigenèreEncode.mjs b/src/core/operations/VigenèreEncode.mjs index db212fe2..effcb0c6 100644 --- a/src/core/operations/VigenèreEncode.mjs +++ b/src/core/operations/VigenèreEncode.mjs @@ -39,36 +39,30 @@ class VigenèreEncode extends Operation { * @returns {string} */ run(input, args) { - const alphabet = "abcdefghijklmnopqrstuvwxyz", - key = args[0].toLowerCase(); - let output = "", - fail = 0, - keyIndex, - msgIndex, - chr; + const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; + const key = args[0].toLowerCase(); + let output = ""; + let fail = 0; + let keyIndex, msgIndex, chr; if (!key) throw new OperationError("No key entered"); - if (!/^[a-zA-Z]+$/.test(key)) throw new OperationError("The key must consist only of letters"); + if (!/^[a-zA-Z0-9]+$/.test(key)) throw new OperationError("The key must consist only of letters and numbers"); for (let i = 0; i < input.length; i++) { - if (alphabet.indexOf(input[i]) >= 0) { - // Get the corresponding character of key for the current letter, accounting - // for chars not in alphabet + const currentChar = input[i]; + const lowerChar = currentChar.toLowerCase(); + + if (alphabet.indexOf(lowerChar) >= 0) { + // Get the corresponding character of key for the current letter chr = key[(i - fail) % key.length]; - // Get the location in the vigenere square of the key char keyIndex = alphabet.indexOf(chr); - // Get the location in the vigenere square of the message char - msgIndex = alphabet.indexOf(input[i]); - // Get the encoded letter by finding the sum of indexes modulo 26 and finding - // the letter corresponding to that - output += alphabet[(keyIndex + msgIndex) % 26]; - } else if (alphabet.indexOf(input[i].toLowerCase()) >= 0) { - chr = key[(i - fail) % key.length].toLowerCase(); - keyIndex = alphabet.indexOf(chr); - msgIndex = alphabet.indexOf(input[i].toLowerCase()); - output += alphabet[(keyIndex + msgIndex) % 26].toUpperCase(); + msgIndex = alphabet.indexOf(lowerChar); + const encodedChar = alphabet[(keyIndex + msgIndex) % alphabet.length]; + + // Preserve case for letters + output += currentChar === lowerChar ? encodedChar : encodedChar.toUpperCase(); } else { - output += input[i]; + output += currentChar; // Keep non-alphabetic characters as is fail++; } } @@ -101,7 +95,6 @@ class VigenèreEncode extends Operation { highlightReverse(pos, args) { return pos; } - } export default VigenèreEncode;