Last active
August 29, 2016 16:11
-
-
Save gadtfly/2e6428d9fadddb1c64181a768ee70f5a to your computer and use it in GitHub Desktop.
Using ES6 generator for keystream -- from: https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/
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
| 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