-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
104 lines (93 loc) · 2.61 KB
/
index.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const fs = require("fs");
const { tokenize } = require("esprima");
const { minify } = require("terser");
const {
getCharsUntilNextNonSpace,
getCharsUntilNextSpace,
needsSpaceAfter,
getAsciiArtInfo,
} = require("./helpers");
let codeTokens;
let asciiArt;
async function art(inFile, outFile, asciiFile) {
let code = fs.readFileSync(inFile).toString();
let isPossible = true;
// minify the code because i.e. long variable names make problems
code = (await minify(code, { sourceMap: true })).code;
codeTokens = tokenize(code);
asciiArt = fs.readFileSync(asciiFile).toString();
let asciiArtInfo = getAsciiArtInfo(asciiArt);
codeTokens.map((token) => {
if (token.value.length > asciiArtInfo.width) {
isPossible = false;
}
});
if (isPossible) {
insertToken(0);
fs.writeFile(outFile, outArray.join(""), () => {});
} else {
console.log("Impossible.");
}
}
let outArray = [];
let asciiPos = 0;
function insertToken(i) {
const t = codeTokens[i];
if (
i >= codeTokens.length &&
asciiPos < getAsciiArtInfo(asciiArt).totalNumberOfChars
) {
if (asciiArt[asciiPos] == "#") {
let charsUntilSpace = getCharsUntilNextSpace(asciiArt.slice(asciiPos));
if (charsUntilSpace >= 4) {
outArray.push(`/*${"#".repeat(charsUntilSpace - 4)}*/`);
asciiPos += charsUntilSpace;
insertToken(i);
}
} else if (asciiArt[asciiPos] == " ") {
let charsUntilNonSpace = getCharsUntilNextNonSpace(
asciiArt.slice(asciiPos)
);
outArray.push(" ".repeat(charsUntilNonSpace));
asciiPos += charsUntilNonSpace;
insertToken(i);
} else if (asciiArt[asciiPos] == "\n") {
outArray.push("\n");
asciiPos++;
insertToken(i);
}
} else {
if (asciiArt[asciiPos] == "#") {
let charsUntilSpace = getCharsUntilNextSpace(asciiArt.slice(asciiPos));
if (charsUntilSpace > t.value.length) {
outArray.push(t.value);
asciiPos += t.value.length;
if (needsSpaceAfter(t, codeTokens[i + 1])) {
outArray.push(" ");
asciiPos++;
}
insertToken(i + 1);
} else if (charsUntilSpace >= 4) {
outArray.push(`/*${"#".repeat(charsUntilSpace - 4)}*/`);
asciiPos += charsUntilSpace;
insertToken(i);
} else {
outArray.push(" ".repeat(charsUntilSpace));
asciiPos += charsUntilSpace;
insertToken(i);
}
} else if (asciiArt[asciiPos] == " ") {
let charsUntilNonSpace = getCharsUntilNextNonSpace(
asciiArt.slice(asciiPos)
);
outArray.push(" ".repeat(charsUntilNonSpace));
asciiPos += charsUntilNonSpace;
insertToken(i);
} else if (asciiArt[asciiPos] == "\n") {
outArray.push("\n");
asciiPos++;
insertToken(i);
}
}
}
art("index.js", "test.js", "ascii.txt");