How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in TypeScript

1 Answer

0 votes
/*
ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
applying ROT13 twice restores the original text (it is its own inverse).
*/

/**
 * Transforms a string using the ROT13 substitution cipher.
 * 
 * @param text - The input string to transform.
 * @returns The transformed ROT13 string.
 */
function rot13(text: string): string {
    if (typeof text !== 'string') {
        throw new TypeError('Input must be a string');
    }

    // Use regex to match all alphabetic characters and replace them in-place
    return text.replace(/[a-zA-Z]/g, (char: string): string => {
        // Determine the ASCII base code ('A' is 65, 'a' is 97) with explicit typing
        const base: number = char <= 'Z' ? 65 : 97;
        
        // Extract character code and calculate shifted position explicitly
        const charCode: number = char.charCodeAt(0);
        const shiftedCode: number = ((charCode - base + 13) % 26) + base;
        
        return String.fromCharCode(shiftedCode);
    });
}

// Input string specified with an explicit type annotation
const message: string = "Hello, World! 123";

console.log(`Original:  ${message}`);

// Apply ROT13 encryption
const encrypted: string = rot13(message);
console.log(`ROT13:     ${encrypted}`);

// ROT13 is its own inverse; applying it again decrypts the message
const decrypted: string = rot13(encrypted);
console.log(`Decrypted: ${decrypted}`);


/*
run:

Original:  Hello, World! 123
ROT13:     Uryyb, Jbeyq! 123
Decrypted: Hello, World! 123

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...