Brilliant
by Eugene Vilder
JavaScript
const keyboard = "1234567890QWERTYUIOPASDFGHJKL;ZXCVBNM,./";
const Typer = {
keyMap: {},
keyboard,
split() {
const res = [ [], [], [], [] ];
let row = 0;
for (let i = 0; i < this.keyboard.length; i++) {
const char = this.keyboard[i];
res[row].push( char );
if (i % 10 === 9) {
row++;
}
}
return res;
},
flipHorizontally() {
let res = "";
this.split().forEach( ( row ) => {
return row.reverse().forEach( ( char ) => {
res += char;
} );
} );
this.keyboard = res;
},
flipVertically() {
let res = "";
this.split().reverse().forEach( ( row ) => {
return row.forEach( ( char ) => {
res += char;
} );
} );
this.keyboard = res;
},
shift( step ) {
this.keyboard = this.keyboard.slice( step ) + this.keyboard.slice( 0, step )
},
createMap() {
for (let i in this.keyboard) {
const char = this.keyboard[i];
this.keyMap[char] = Number( i );
}
},
encode( sequence, text ) {
text = text.toUpperCase();
this.createMap();
[ 'HH', 'VV', 'VHVH', 'HVHV' ].forEach( ( combination ) => {
sequence = sequence.replaceAll( combination, '' );
} );
if (!sequence.length) {
return text;
}
sequence.match( /V|H|S-?\d{1,}/gmi ).forEach( ( match ) => {
match = match.toUpperCase();
if (match === 'V') {
this.flipVertically();
} else if (match === 'H') {
this.flipHorizontally();
} else {
const step = Number( match.slice( 1 ) );
this.shift( step );
}
} );
let encodedText = "";
for (let i in text) {
const char = text[i];
...