Created
June 7, 2022 10:28
-
-
Save thedom85/0857ca4e205cd475027f55b964d71615 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/train/javascript | |
function VigenèreCipher(key, abc) { | |
this.encode = function (message) { | |
let upperCase = message == message.toUpperCase(); | |
message = message.toLowerCase(); | |
let result = '' | |
for (let i = 0, j = 0; i < message.length; i++) { | |
const c = message.charAt(i) | |
if(abc.indexOf(c) != -1){ | |
let sum = abc.indexOf(c) + abc.indexOf(key[j].toLowerCase()); | |
if(sum > abc.length-1) { | |
sum = sum - (abc.length) | |
} | |
result += abc[sum]; | |
} else{ | |
result += c; | |
} | |
j = ++j % key.length | |
} | |
return upperCase?result.toUpperCase():result.toLowerCase(); | |
}; | |
this.decode = function (message) { | |
let upperCase = message == message.toUpperCase(); | |
message = message.toLowerCase(); | |
let result = '' | |
for (let i = 0, j = 0; i < message.length; i++) { | |
const c = message.charAt(i); | |
console.log(c ,"-", abc.indexOf(c) != -1) | |
if(abc.indexOf(c) != -1){ | |
let sum = abc.indexOf(c) - abc.indexOf(key[j].toLowerCase()); | |
if(sum < 0) { | |
sum = sum + (abc.length) | |
} | |
result += abc[sum]; | |
}else{ | |
result += c; | |
} | |
console.log("result", result); | |
j = ++j % key.length | |
} | |
return upperCase?result.toUpperCase():result.toLowerCase(); | |
}; | |
} | |
var abc, key; | |
abc = "abcdefghijklmnopqrstuvwxyz"; | |
key = "password" | |
c = new VigenèreCipher(key, abc); | |
console.log(c.encode('codewars'), 'rovwsoiv'); | |
console.log(c.encode('CODEWARS'), 'ROVWSOIV'); | |
console.log(c.decode('rovwsoiv'), 'codewars'); | |
console.log(c.decode('ROVWSOIV'), 'CODEWARS'); | |
abc = "アイウエオァィゥェォカキクケコサシスセソタチツッテトナニヌネノハヒフヘホマミムメモヤャユュヨョラリルレロワヲンー"; | |
key = "カタカナ" | |
c = new VigenèreCipher(key, abc); | |
console.log("result :",c.decode('javscript'),"javscript"); | |
console.log("result :",c.encode('javscript'),"javscript"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment