Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reversing the alphabet from back to front and front to back in JavaScript
In JavaScript, we can create a function that finds the "mirror" position of an alphabet character. Given a letter, we find its position from the start and return the letter at the same position from the end.
Understanding the Logic
The alphabet has 26 letters. If we split it into two halves, each letter in the first half corresponds to a letter in the second half when reversed. For example, 'a' (1st position) corresponds to 'z' (26th position), 'b' corresponds to 'y', and so on.
Example Implementation
Here's how we can implement this functionality:
const alpha = 'g';
const findCounterPart = (alpha = '') => {
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
let firstpart = alphabet.substring(0, 13).split('');
let secondpart = alphabet.substring(13).split('').reverse();
let solution = '';
if (firstpart.indexOf(alpha) !== -1) {
solution = secondpart[firstpart.indexOf(alpha)];
} else {
solution = firstpart[secondpart.indexOf(alpha)];
}
return solution;
};
console.log(findCounterPart(alpha));
t
Alternative Approach Using Character Codes
We can also solve this using ASCII character codes for a more mathematical approach:
const findCounterPartAscii = (letter) => {
// Convert to lowercase and get ASCII code
const charCode = letter.toLowerCase().charCodeAt(0);
// Calculate mirror position: 'a' + 'z' = 97 + 122 = 219
const mirrorCharCode = 219 - charCode;
return String.fromCharCode(mirrorCharCode);
};
console.log(findCounterPartAscii('g')); // t
console.log(findCounterPartAscii('a')); // z
console.log(findCounterPartAscii('z')); // a
t z a
How It Works
The first method splits the alphabet into two halves and creates a mapping between corresponding positions. The second method uses the mathematical relationship that the sum of ASCII values for mirror letters equals 219 (97 + 122, where 97 is 'a' and 122 is 'z').
Testing Multiple Cases
const testCases = ['a', 'g', 'm', 'n', 'z'];
testCases.forEach(letter => {
console.log(`${letter} ? ${findCounterPart(letter)}`);
});
a ? z g ? t m ? n n ? m z ? a
Conclusion
Both approaches effectively find the mirror position of alphabet characters. The ASCII method is more concise, while the string manipulation approach is more intuitive for understanding the concept.
