Search code examples
javascriptarrayscaesar-cipher

Caesar cipher with JavaScript


I've checked different websites with different code variations, but couldn't find the appropriate answer. I need to create 2 functions where : -1st function will cipher the given message with key, which is string; e.g. If Message=hello and key=123(so keys will be 1, 2, 3), output should be 'igomq' -2nd one will decipher I've already wrote code, but this only works when key is '123'. How can it be improved?

`

function cipher(message, key) {
    const arrOfKeys = key.split("")
    const cipheredMessage = []
    let newLettersArr = []
    for (let i = 0; i < message.length; i++) {
        let remain = i % arrOfKeys.length
        if (remain >= 0) {
            let newLetter = message.charCodeAt(i) + (remain + 1)
            newLettersArr.push(newLetter)
        }
    }
    newLettersArr.forEach((letter) => {
        let cipheredLetter = String.fromCharCode(letter)
        cipheredMessage.push(cipheredLetter)
    })
    return cipheredMessage
}

function deCipher(message, key) {
    const arrOfKeys = key.split("")
    const cipheredMessage = []
    let newLettersArr = []
    for (let i = 0; i < message.length; i++) {
        let remain = i % arrOfKeys.length
        if (remain >= 0) {
            let newLetter = message.charCodeAt(i) - (remain + 1)
            newLettersArr.push(newLetter)
        }
    }
    newLettersArr.forEach((letter) => {
        let cipheredLetter = String.fromCharCode(letter)
        cipheredMessage.push(cipheredLetter)
    })
    return cipheredMessage
}

console.log(cipher("hello", "123"))
console.log(deCipher("igomq", "123"))

`


Solution

  • It looks like you need get the value from arrOfKeys for incrementing/decrementing the char code.

    Beside this, you need to remove the check for having remain not zero. This is wrong, because it is the index for the incrementing/decementing value.

    In deCipher I show you a more compact result.

    function cipher(message, key) {
        const arrOfKeys = key.split("");
        const cipheredMessage = [];
        let newLettersArr = [];
        for (let i = 0; i < message.length; i++) {
            let remain = i % arrOfKeys.length;
            let newLetter = message.charCodeAt(i) + +arrOfKeys[remain];
            newLettersArr.push(newLetter);
        }
        newLettersArr.forEach((letter) => {
            let cipheredLetter = String.fromCharCode(letter);
            cipheredMessage.push(cipheredLetter);
        });
        return cipheredMessage;
    }
    
    function deCipher(message, key) {
        const keys = Array.from(key, Number);
        return Array.from(
            message,
            (c, i) => String.fromCharCode(c.charCodeAt(0) - keys[i % keys.length])
        )
    }
    
    console.log(cipher("hello", "5123"))
    console.log(deCipher("mfnot", "5123"))