Created
October 14, 2017 20:40
-
-
Save chocopuff2020/532604f9e69003b54467c2a02016ea0b to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
"use strict"; | |
const meow = require("meow"); | |
const chalk = require("chalk"); | |
const _ = require("lodash"); | |
const cli = meow({ | |
help: ["Usage", " $ convert [commands] [options]"] | |
}); | |
let command_string = cli.input[1]; | |
let input_string = cli.input[2]; | |
// =========================================================== | |
const keyboard = [ | |
"1", | |
"2", | |
"3", | |
"4", | |
"5", | |
"6", | |
"7", | |
"8", | |
"9", | |
"0", | |
"Q", | |
"W", | |
"E", | |
"R", | |
"T", | |
"Y", | |
"U", | |
"I", | |
"O", | |
"P", | |
"A", | |
"S", | |
"D", | |
"F", | |
"G", | |
"H", | |
"J", | |
"K", | |
"L", | |
";", | |
"Z", | |
"X", | |
"C", | |
"V", | |
"B", | |
"N", | |
"M", | |
",", | |
".", | |
"/" | |
]; | |
const keyboardMap = {}; | |
keyboard.forEach(function(val, idx) { | |
keyboardMap[val] = idx; | |
}); | |
function coordinateToIndex(x, y) { | |
return 10 * x + y; | |
} | |
function indexToCoordinate(i) { | |
let x = Math.floor(i / 10); | |
let y = i % 10; | |
return [x, y]; | |
} | |
function horizontalFlip(i) { | |
const [x, y] = indexToCoordinate(i); | |
const newY = 9 - y; | |
const result = coordinateToIndex(x, newY); | |
return result; | |
} | |
function verticalFlip(i) { | |
const [x, y] = indexToCoordinate(i); | |
const newX = 3 - x; | |
return coordinateToIndex(newX, y); | |
} | |
function shift(n, i) { | |
const newIdx = i - n; | |
return newIdx < 0 ? shift(40, newIdx) : newIdx % 40; | |
} | |
const re = /(H|V|S(-?\d+))/g; | |
function getMutator(rule) { | |
let m; | |
const result = []; | |
while ((m = re.exec(rule))) { | |
if (m[1] === "H") { | |
result.push(horizontalFlip); | |
continue; | |
} | |
if (m[1] === "V") { | |
result.push(verticalFlip); | |
continue; | |
} | |
if (m[1].indexOf("S") === 0) { | |
result.push(shift.bind(null, parseInt(m[2]))); | |
continue; | |
} | |
} | |
return _.flow(result); | |
} | |
function translateString(rule, text) { | |
const mutator = getMutator(rule); | |
const result = text.split("").map(function(char) { | |
const charIdx = keyboardMap[char.toUpperCase()]; | |
const newIdx = mutator(charIdx); | |
return keyboard[newIdx]; | |
}); | |
return result.join(""); | |
} | |
console.log(translateString(command_string, input_string)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment