Skip to content

Instantly share code, notes, and snippets.

@vladgovor77771
Created April 23, 2021 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladgovor77771/eb98fc8a66da1aa61dea1544b0ea1e55 to your computer and use it in GitHub Desktop.
Save vladgovor77771/eb98fc8a66da1aa61dea1544b0ea1e55 to your computer and use it in GitHub Desktop.
remove_fake_ifs.js
const fs = require("fs");
const input = fs.readFileSync("test.js").toString().split("\n");
const ifRegex = /^(\s*)if \((.{7}) (===|!==) (.{7})\)( {|)/;
const elseRegex = /^(\s*)(} else {|} else|else {|else)/;
const removeElseBlock = (index, matches) => {
let spacesCount = matches[1].length;
// remove "if ... statement"
if (matches[5] == " {") {
input.splice(index, 1);
} else {
input[index] = input[index].replace(matches[0].substring(spacesCount), "");
}
// remove "else"
for (let j = index + 1; j < input.length; j++) {
let elseMatches = input[j].match(elseRegex);
if (elseMatches != null && elseMatches[1].length == spacesCount) {
if (elseMatches[2] == "else" || elseMatches[2] == "} else") {
input.splice(j, 1);
} else if (elseMatches[2] == "else {" || elseMatches[2] == "} else {") {
let k = j + 1;
for (; k < input.length; k++) {
if (input[k].indexOf(" ".repeat(spacesCount) + "}") == 0) break;
}
input.splice(j, k - j + 1);
}
break;
}
}
};
const removeIfBlock = (index, matches) => {
let spacesCount = matches[1].length;
let elseStartIndex = index + 1;
for (; elseStartIndex < input.length; elseStartIndex++) {
let elseMatches = input[elseStartIndex].match(elseRegex);
if (elseMatches != null && elseMatches[1].length == spacesCount) {
if (elseMatches[2] == "else" || elseMatches[2] == "} else") {
input[elseStartIndex] = input[elseStartIndex].replace(elseMatches[2], "");
input.splice(index, elseStartIndex - index);
} else if (elseMatches[2] == "else {" || elseMatches[2] == "} else {") {
let k = elseStartIndex + 1;
for (; k < input.length; k++) {
if (input[k].indexOf(" ".repeat(spacesCount) + "}") == 0) break;
}
input.splice(k, 1);
input.splice(index, elseStartIndex - index + 1);
}
break;
}
}
};
for (var i = 0; i < input.length; i++) {
const matches = input[i].match(ifRegex);
if (matches != null) {
if (matches[3] == "===") {
if (matches[2] === matches[4]) removeElseBlock(i, matches);
else removeIfBlock(i, matches);
}
if (matches[3] == "!==") {
if (matches[2] !== matches[4]) removeElseBlock(i, matches);
else removeIfBlock(i, matches);
}
i--;
}
}
fs.writeFileSync("out.js", input.join("\n"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment