September 10th 2018
Write a class that, when given a string, will return an uppercase string with each letter shifted forward in the alphabet by however many spots the cipher was initialized to.
For example:
var c = new CaesarCipher(5); // creates a CipherHelper with a shift of five
c.encode('Codewars'); // returns 'HTIJBFWX'
c.decode('BFKKQJX'); // returns 'WAFFLES'
If something in the string is not in the alphabet (e.g. punctuation, spaces), simply leave it as is. The shift will always be in range of [1, 26].
생성자 함수가 있고, 이 생성자 객체의 프로토타입에 암호를 만들고 해독하는 메서드를 추가하는 문제입니다. 암호를 만들고 해석할 때, 알파벳순으로 인자로 전달받은 숫자만큼 이동시키면 됩니다.
var CaesarCipher = function(shift) {
this.encode = function(str) {
var strArr = str.toLocaleUpperCase().split('');
strArr = strArr.map(function(cur) {
var num = cur.charCodeAt();
if (num >= 65 && num <= 90) {
num += shift;
return num > 90 ? (num -= 26) : num;
} else {
return num;
}
});
return strArr.reduce(function(acc, cur) {
return acc + String.fromCharCode(cur);
}, '');
};
this.decode = function(str) {
var strArr = str.toLocaleUpperCase().split('');
strArr = strArr.map(function(cur) {
var num = cur.charCodeAt();
if (num >= 65 && num <= 90) {
num -= shift;
return num < 65 ? (num += 26) : num;
} else {
return num;
}
});
return strArr.reduce(function(acc, cur) {
return acc + String.fromCharCode(cur);
}, '');
};
};