Files
JavaScript/Ciphers/VigenereCipher.js
Roland Hummel 86d333ee94 feat: Test running overhaul, switch to Prettier & reformat everything (#1407)
* chore: Switch to Node 20 + Vitest

* chore: migrate to vitest mock functions

* chore: code style (switch to prettier)

* test: re-enable long-running test

Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime!

see #1193

* chore: code style

* chore: fix failing tests

* Updated Documentation in README.md

* Update contribution guidelines to state usage of Prettier

* fix: set prettier printWidth back to 80

* chore: apply updated code style automatically

* fix: set prettier line endings to lf again

* chore: apply updated code style automatically

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
2023-10-04 02:38:19 +05:30

92 lines
2.2 KiB
JavaScript

/**
* Check if the Character is letter or not
* @param {String} str - character to check
* @return {object} An array with the character or null if isn't a letter
*/
function isLetter(str) {
return str.length === 1 && str.match(/[a-zA-Z]/i)
}
/**
* Check if is Uppercase or Lowercase
* @param {String} character - character to check
* @return {Boolean} result of the checking
*/
function isUpperCase(character) {
if (character === character.toUpperCase()) {
return true
}
if (character === character.toLowerCase()) {
return false
}
}
/**
* Encrypt a Vigenere cipher
* @param {String} message - string to be encrypted
* @param {String} key - key for encrypt
* @return {String} result - encrypted string
*/
function encrypt(message, key) {
let result = ''
for (let i = 0, j = 0; i < message.length; i++) {
const c = message.charAt(i)
if (isLetter(c)) {
if (isUpperCase(c)) {
result += String.fromCharCode(
((c.charCodeAt(0) + key.toUpperCase().charCodeAt(j) - 2 * 65) % 26) +
65
) // A: 65
} else {
result += String.fromCharCode(
((c.charCodeAt(0) + key.toLowerCase().charCodeAt(j) - 2 * 97) % 26) +
97
) // a: 97
}
} else {
result += c
}
j = ++j % key.length
}
return result
}
/**
* Decrypt a Vigenere cipher
* @param {String} message - string to be decrypted
* @param {String} key - key for decrypt
* @return {String} result - decrypted string
*/
function decrypt(message, key) {
let result = ''
for (let i = 0, j = 0; i < message.length; i++) {
const c = message.charAt(i)
if (isLetter(c)) {
if (isUpperCase(c)) {
result += String.fromCharCode(
90 - ((25 - (c.charCodeAt(0) - key.toUpperCase().charCodeAt(j))) % 26)
)
} else {
result += String.fromCharCode(
122 -
((25 - (c.charCodeAt(0) - key.toLowerCase().charCodeAt(j))) % 26)
)
}
} else {
result += c
}
j = ++j % key.length
}
return result
}
export { encrypt, decrypt }
// > encrypt('Hello World!', 'code')
// 'Jsopq Zstzg!'
// > decrypt('Jsopq Zstzg!', 'code')
// 'Hello World!'