Skip to content

Commit 47c1c51

Browse files
authored
merge: Improved ciphers (TheAlgorithms#954)
* feat: imporved algorithm via replace method * test: added two test cases
1 parent b85bf49 commit 47c1c51

File tree

2 files changed

+34
-25
lines changed

2 files changed

+34
-25
lines changed

Ciphers/Atbash.js

+17-25
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

Ciphers/test/Atbash.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import Atbash from '../Atbash'
2+
3+
describe('Testing Atbash function', () => {
4+
it('Test - 1, passing the non-string as an argument', () => {
5+
expect(() => Atbash(0x345)).toThrow()
6+
expect(() => Atbash(123)).toThrow()
7+
expect(() => Atbash(123n)).toThrow()
8+
expect(() => Atbash(false)).toThrow()
9+
expect(() => Atbash({})).toThrow()
10+
expect(() => Atbash([])).toThrow()
11+
})
12+
13+
it('Test - 2, passing all alphabets', () => {
14+
expect(Atbash('HELLO WORLD')).toBe('SVOOL DLIOW')
15+
expect(Atbash('The quick brown fox jumps over the lazy dog')).toBe('Gsv jfrxp yildm ulc qfnkh levi gsv ozab wlt')
16+
})
17+
})

0 commit comments

Comments
 (0)