Skip to content

Instantly share code, notes, and snippets.

@mieszko4
Last active March 3, 2016 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mieszko4/c891161ec5e39927670e to your computer and use it in GitHub Desktop.
Save mieszko4/c891161ec5e39927670e to your computer and use it in GitHub Desktop.
Encoder with generator
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