Skip to content

Instantly share code, notes, and snippets.

@gadtfly
Last active August 29, 2016 16:11
Show Gist options
  • Select an option

  • Save gadtfly/2e6428d9fadddb1c64181a768ee70f5a to your computer and use it in GitHub Desktop.

Select an option

Save gadtfly/2e6428d9fadddb1c64181a768ee70f5a to your computer and use it in GitHub Desktop.
Using ES6 generator for keystream -- from: https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/
function mod(x,y) {
return ((x % y) + y) % y;
}
function VigenèreCipher(key, alphabet) {
this.keystream = function*() {
while(true) {
yield* key.split('');
}
};
this.shiftChar = function(c1, c2, shift) {
if(alphabet.includes(c1)) {
return alphabet.charAt(mod(shift(alphabet.indexOf(c1), alphabet.indexOf(c2)), alphabet.length));
} else {
return c1;
}
};
this.code = function(s, shift) {
var keystream = this.keystream();
return s.split('').map(function(c){
return this.shiftChar(c, keystream.next().value, shift);
}, this).join('');
};
this.encode = function(s) {
return this.code(s, function(x,y){return x+y;});
};
this.decode = function(s) {
return this.code(s, function(x,y){return x-y;});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment