Instructions
Create an implementation of the Vigenère cipher.
The Vigenère cipher is a simple substitution cipher.
Our Solution
export class SimpleCipher {
constructor(key) {
if (key === undefined) {
this.key = Array.from({ length: 100 }, () => String.fromCharCode(Math.floor(Math.random() * 26) + 97)).join('');
} else {
this.key = key;
}
}
encode(text) {
return text.split('').map((char, i) => {
const shift = this.key.charCodeAt(i % this.key.length) - 97;
return String.fromCharCode(((char.charCodeAt(0) - 97 + shift) % 26) + 97);
}).join('');
}
decode(text) {
return text.split('').map((char, i) => {
const shift = this.key.charCodeAt(i % this.key.length) - 97;
return String.fromCharCode(((char.charCodeAt(0) - 97 - shift + 26) % 26) + 97);
}).join('');
}
}
Source: Exercism javascript/simple-cipher