message: my secret code i want to secure
key: passwordpasswordpasswordpasswor
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var key = 'password';
// creates a cipher helper with each letter substituted
// by the corresponding character in the key
var c = new VigenèreCipher(key, alphabet);
c.encode('codewars'); // returns 'rovwsoiv'
c.decode('laxxhsj'); // returns 'waffles'
키값을 받아서 키값+평문값 단 알파벳에 포함안된녀석을 그대로 출력(abc
변수)
function VigenèreCipher(key, abc) {
var repeatpw = (s)=> s.split('').map((_,i)=>key[i%key.length]);
var convert = (str, f)=> repeatpw(str).map(f).join('');
this.encode = function (str) {
return convert(str, (p,i)=> abc.indexOf(str[i])>=0? abc[(abc.indexOf(p)+abc.indexOf(str[i]))%abc.length] : str[i]);
};
this.decode = function (str) {
return convert(str, (p,i)=> abc.indexOf(str[i])>=0? abc[(abc.length-abc.indexOf(p)+abc.indexOf(str[i]))%abc.length] : str[i]);
};
}
제일 위에있던 베스트는 겁나게..긴데;;; 이것보단, 좀 내려가서 찾은 답이 훨 나은듯
function VigenèreCipher(key, alphabet) {
function encode(direction, inStr) {
var inChar, inIdx, outIdx, outChar, keyChar, offset;
var outStr = '';
// Process each character of the input string sequentially
for (var pos = 0; pos < inStr.length; ++pos) {
// Look up input character in the alphabet
inChar = inStr.charAt(pos);
inIdx = alphabet.indexOf(inChar);
// If character isn't in alphabet, just copy it to output
if (inIdx < 0)
outChar = inChar;
else {
// Get the key character for the current position
// and determine the shift distance
keyChar = key.charAt(pos % key.length);
offset = alphabet.indexOf(keyChar);
// Shift the character forwards or backwards in
// the alphabet, wrapping around if necessary
outIdx = inIdx + direction * offset;
if (outIdx >= alphabet.length)
outIdx = outIdx - alphabet.length;
else if (outIdx < 0)
outIdx = outIdx + alphabet.length;
outChar = alphabet.charAt(outIdx);
}
outStr += outChar;
}
return outStr;
}
// Encode by shifting characters forward in the alphabet
this.encode = function(string) {
return encode(1, string);
};
// Decode by shifting characters backwards in the alphabet
this.decode = function(string) {
return encode(-1, string);
};
}
function VigenèreCipher(key, abc) {
this.encode = (str) => encode(1, str);
this.decode = (str) => encode(-1, str);
function encode (mult, str) {
return str.split('').map(function (letter, index) {
var i = abc.indexOf(letter);
return i < 0 ? letter : abc[(abc.length + i + abc.indexOf(key[index % key.length]) * mult) % abc.length];
}).join('');
}
}