17 lines
837 B
TypeScript
17 lines
837 B
TypeScript
export function sanityConvert(code: string, maxLoops: number = 2000) {
|
|
var beforeCondition = "var conditionCount = " + maxLoops + "; \n";
|
|
var insideCondition = "\n --conditionCount; \n if (conditionCount <= 0) { break; } \n";
|
|
|
|
const regex = /(?<!function.*)(while|for|if)(\s*\((?:[^()]|\([^()]*\))*\)\s*)(.*?{[^}]*}|.*?;)/gs;
|
|
const output = code.replace(regex, (match, p1, p2, p3) => {
|
|
let statement = p3.trim();
|
|
if (statement.startsWith('{') && statement.endsWith('}')) {
|
|
statement = statement.replace('{', '{' + insideCondition);
|
|
} else {
|
|
statement = statement.endsWith(';') ? statement.slice(0, -1) : statement;
|
|
statement = `{${insideCondition}${statement};}`;
|
|
}
|
|
return `${beforeCondition}${p1}${p2}${statement}`;
|
|
});
|
|
return output;
|
|
} |