Skip to content

Instantly share code, notes, and snippets.

@Spuffynism
Last active December 18, 2017 19:26
Show Gist options
  • Save Spuffynism/ec293c8813cadf7f0be92e504d76ef5f to your computer and use it in GitHub Desktop.
Save Spuffynism/ec293c8813cadf7f0be92e504d76ef5f to your computer and use it in GitHub Desktop.
Converts a string to a brainfuck program that prints the said string
const COMMAND = {
next: '>',
prev: '<',
increment: '+',
decrement: '-',
print: '.',
accept: ',',
loop: '[',
endLoop: ']'
};
const TEN_INCREMENT = '+++++ +++++';
const STANDARD_LOOP = COMMAND.loop + COMMAND.next + TEN_INCREMENT + COMMAND.prev +
COMMAND.decrement + COMMAND.endLoop + COMMAND.next;
class Converter {
convert (str) {
let prevCharCode = 0;
return str.split("").reduce((acc, c) => {
let result = acc + this._charToBrainfuck(c.charCodeAt(0), prevCharCode);
prevCharCode = c.charCodeAt(0);
return result;
}, "");
}
_charToBrainfuck (charCode, prevCharCode) {
let diff = Math.abs(charCode - prevCharCode);
let up = prevCharCode < charCode;
let tens = Math.floor(diff / 10);
let ones = diff - tens * 10;
let result = (tens > 0 && prevCharCode !== 0) ? COMMAND.prev : "";
for (let i = 0; i < tens; i++)
result += up ? COMMAND.increment : COMMAND.decrement;
if (tens > 0)
result += STANDARD_LOOP;
for (let i = 0; i < ones; i++)
result += up ? COMMAND.increment : COMMAND.decrement;
return result + COMMAND.print;
}
};
console.log(new Converter().convert("Convert me"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment