Shift cipher bug?

Any ideas why it doesn’t accept my code. Seems like it do work…




class ShiftCipher {
    constructor(shift){
        this._shift = shift;
    };


    isLiteral(code){
        if( (code > 64 && code < 91) || (code > 96 && code < 123) )
            return true;        
        return false;   
    };

    problemChar(code, shift) { 
        
        let direction = Math.abs(shift) / shift;
        let final = code;

        for (let i = 0; i < Math.abs(shift); i++) {
            final += direction;
            if (final > 90 && final < 97) 
                final += 6*direction;

            if (final < 65 || final > 122)
                final -= 58*direction;            
        } ;
        
        return final;
    };

    
    shiftTheChar(code, shift){

        if (!this.isLiteral(code)) return String.fromCharCode(code);        //not a letter?

        let final = this.problemChar(code,shift);
        return String.fromCharCode(final); 
    };

    processStr(str, type){
        let chCode = 0;
        let changedStr = '';
        let changedChar = '';

        let shift = this._shift;
        if (type === 0) shift *= -1;       // 1-encrypt, 0-decrypt

        for (let i = 0; i < str.length; i++) {
            chCode = str.charCodeAt(i);
            changedChar = this.shiftTheChar(chCode, shift); 
            changedStr += changedChar;  
        }
        return changedStr;
    };


    encrypt(plainText){
        let shifted = this.processStr(plainText, 1);  
        return shifted.toUpperCase();         
    };
    

    //returns lower case unshifted text
    decrypt(encText){
        let shifted = this.processStr(encText, 0);
        console.log(shifted.toLowerCase()); 
        return shifted.toLowerCase;
    }
}

//Test

const cipher = new ShiftCipher(1);
cipher.decrypt('a');

Hi Elena,
it expects a lower case ‘z’.
A look at your code confirms my suspicion that the letter was not set to lower case.

Notice the difference between what you logged to the console and what you returned?

3 Likes

you just left off the parenthesis on tolowercase ]. Youre not invoking to lower case youre returnng the memorry address of the function (on the last line of your decrypt fn)

1 Like

Just to give a shorter solution I came up with.

class ShiftCipher {
  constructor(shift) {
    this.shift = shift < 0 ? shift % 26 + 26 : shift % 26;
  }

  encrypt(string) { return this.crypt(string, this.shift).toUpperCase(); }

  decrypt(string) { return this.crypt(string, -this.shift).toLowerCase(); }

  crypt(string, shift) {
    shift = shift > 0 ? shift - 65 : shift + 65;
    return string.toUpperCase().split("").map(letter => {
      if (/[A-Z]/.test(letter)) { var codeChar = (letter.charCodeAt(0) + shift) % 26 + 65 }
      if (codeChar) { return String.fromCharCode(codeChar); }
      return letter;
    }).join("");
  }
  
}
1 Like

Thank you all guys! Case solved :slight_smile: