Skip to content

Commit 5cedaa9

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

1 file changed

Lines changed: 17 additions & 25 deletions

File tree

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)