-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToBrainfuck.js
More file actions
74 lines (65 loc) · 2.5 KB
/
StringToBrainfuck.js
File metadata and controls
74 lines (65 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* StringToBrainfuck.js
*
* Converts a string to a Brainfuck script that will output said string.
* usage: node StringToBrainfuck.js your string here
*
* @author Maxamilian Demian <max@maxdemian.com>
* @link https://www.maxodev.org
* @link https://github.com/Maxoplata/StringToBrainfuck
*/
// if we have arguments passed to the script
if (process.argv.length > 2) {
const inputString = process.argv.splice(2).join(' ');
// the Brainfuck code we will output in the end
let bfCode = '';
/**
* our current location on the "tape" (pointer 1).
* we use pointer 0 as a multiplier for pointer 1 to shorten the output script.
*
* e.g.
* A(65) = ++++++[>++++++++++<-]>+++++.
* ++++++ = add 6 to current pointer value (pointer 0)
* [ = while current pointer (pointer 0)'s value > 0
* > = move pointer ahead one (to pointer 1)
* ++++++++++ = add 10 to current pointer value (pointer 1)
* < = move pointer back one (to pointer 0)
* - = subtract 1 from current pointervalue (pointer 0)
* ] = end while loop
* > = move pointer ahead one (to pointer 1)
* +++++ = add 5 to current pointer value (pointer 1)
* . = print out character at current pointer value (pointer 1, value 65, char 'A')
*
* instead of:
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
*/
let currentLocation = 0;
// iterate through each character in the string
[...inputString].forEach((char, i) => {
// get the Unicode code for the current character
const charVal = char.charCodeAt(0);
if (charVal > currentLocation) {
// move ahead on the "tape" to build the character
bfCode += '+'.repeat(Math.floor((charVal - currentLocation) / 10));
bfCode += '[>++++++++++<-]>';
bfCode += '+'.repeat((charVal - currentLocation) % 10);
} else if (charVal < currentLocation) {
// move backwards on the "tape" to build the character
bfCode += '+'.repeat(Math.floor((currentLocation - charVal) / 10));
bfCode += '[>----------<-]>';
bfCode += '-'.repeat((currentLocation - charVal) % 10);
} else {
// delete the "<" from the previous command as we are on the same character
// and we will want to print it out again
bfCode = bfCode.slice(0, -1);
}
// print out the current character
bfCode += '.';
// if we are not on the last letter of the string, move pointer position back to 0
if (i < (inputString.length - 1)) {
bfCode += '<';
}
currentLocation = charVal;
});
console.log(bfCode);
}