Last active
March 3, 2016 03:26
-
-
Save mieszko4/c891161ec5e39927670e to your computer and use it in GitHub Desktop.
Encoder with generator
This file contains 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
Number.prototype.mod = function(n) { | |
return ((this % n) + n) % n; | |
}; | |
function encode(string, generator, cycle=10, reverse=false) { | |
let sequence = generator(); | |
let start = ' '.charCodeAt(); | |
let end = '~'.charCodeAt(); | |
return Array.from(string).map((c, i) => { | |
return ( | |
( | |
c.charCodeAt() - start + (reverse ? -1 : 1) * sequence.next(i % cycle === 0).value | |
).mod(end - start) | |
) + start; | |
}).map(n => String.fromCharCode(n)) | |
.join(''); | |
} | |
// Usage: | |
//1. generator | |
function* fibonacci () { | |
let fn1 = 0; | |
let fn2 = 1; | |
while (true) { | |
var current = fn1; | |
fn1 = fn2; | |
fn2 = current + fn1; | |
var reset = yield current; | |
if (reset) { | |
fn1 = 0; | |
fn2 = 1; | |
} | |
} | |
} | |
//2. cycle | |
let cycle = 10; | |
//3. encode | |
encode('Hello World!', fibonacci, cycle); //outputs: Hfmnr%_|)0d! | |
//4. decode - reverse of encode | |
encode('Hfmnr%_|)0d!', fibonacci, cycle, true); //outputs: Hello World! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment