Skip to content

Commit 5cedaa9

Browse files
committed
feat: imporved algorithm via replace method
1 parent 9681688 commit 5cedaa9

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed

Ciphers/Atbash.js

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,22 @@
1-
/*
2-
The Atbash cipher is a particular type of monoalphabetic cipher
3-
formed by taking the alphabet and mapping it to its reverse,
4-
so that the first letter becomes the last letter,
5-
the second letter becomes the second to last letter, and so on.
6-
*/
7-
81
/**
9-
* Decrypt a Atbash cipher
10-
* @param {String} str - string to be decrypted/encrypt
11-
* @return {String} decrypted/encrypted string
2+
* @function Atbash - Decrypt a Atbash cipher
3+
* @description - The Atbash cipher is a particular type of monoalphabetic cipher formed by taking the alphabet and mapping it to its reverse, so that the first letter becomes the last letter, the second letter becomes the second to last letter, and so on.
4+
* @param {string} str - string to be decrypted/encrypt
5+
* @return {string} decrypted/encrypted string
6+
* @see - [wiki](https://en.wikipedia.org/wiki/Atbash)
127
*/
13-
function Atbash (message) {
14-
let decodedString = ''
15-
for (let i = 0; i < message.length; i++) {
16-
if (/[^a-zA-Z]/.test(message[i])) {
17-
decodedString += message[i]
18-
} else if (message[i] === message[i].toUpperCase()) {
19-
decodedString += String.fromCharCode(90 + 65 - message.charCodeAt(i))
20-
} else {
21-
decodedString += String.fromCharCode(122 + 97 - message.charCodeAt(i))
22-
}
8+
const Atbash = (str) => {
9+
if (typeof str !== 'string') {
10+
throw new TypeError('Argument should be string')
2311
}
24-
return decodedString
25-
}
2612

27-
export { Atbash }
13+
return str.replace(/[a-z]/gi, (char) => {
14+
if (/[A-Z]/.test(char)) {
15+
return String.fromCharCode(90 + 65 - char.charCodeAt())
16+
}
17+
18+
return String.fromCharCode(122 + 97 - char.charCodeAt())
19+
})
20+
}
2821

29-
// > Atbash('HELLO WORLD')
30-
// 'SVOOL DLIOW'
22+
export default Atbash

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy