Skip to content

Instantly share code, notes, and snippets.

@ehrenmurdick
Created June 15, 2019 22:40
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 ehrenmurdick/f45a8284596be9c6224959f92a346d8f to your computer and use it in GitHub Desktop.
Save ehrenmurdick/f45a8284596be9c6224959f92a346d8f to your computer and use it in GitHub Desktop.
class Encoder {
constructor(key) {
this.key = key;
this.position = 0;
}
encode(msg) {
let res = [];
for(let i = 0; i < msg.length; i++) {
if(msg[i] == ' ') {
res.push(' '.charCodeAt(0));
continue;
}
let c = msg.charCodeAt(i);
c += this.key[this.position];
this.position++;
if(this.position > this.key.length - 1) {
this.position = 0;
}
res.push(c);
}
return String.fromCharCode.apply(this, res);
}
}
class Decoder {
constructor(key) {
this.key = key;
this.position = 0;
}
decode(msg) {
let res = [];
for(let i = 0; i < msg.length; i++) {
if(msg[i] == ' ') {
res.push(' '.charCodeAt(0));
continue;
}
let c = msg.charCodeAt(i);
c -= this.key[this.position];
this.position++;
if(this.position > this.key.length - 1) {
this.position = 0;
}
res.push(c);
}
return String.fromCharCode.apply(this, res);
}
}
class Bus {
constructor() {
const key = [ 1, 7, 38, 42 ];
this.encoder = new Encoder(key);
this.decoder = new Decoder(key);
}
send(msg) {
console.log('position: ' + this.encoder.position);
console.log('======');
console.log('original message:');
console.log(msg);
console.log('------');
const res = this.encoder.encode(msg);
console.log('encoded message:');
console.log(res);
console.log('------');
console.log('decoded message:');
const nm = this.decoder.decode(res);
console.log(nm);
}
}
const bus = new Bus();
bus.send('hello my name is ehren');
bus.send('another');
bus.send('message');
position: 0
======
original message:
hello my name is ehren
------
encoded message:
ilp t bt t lfu
------
decoded message:
hello my name is ehren
position: 2
======
original message:
another
------
encoded message:
p{s
------
decoded message:
another
position: 1
======
original message:
message
------
encoded message:
tth
------
decoded message:
message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment