const fs = require("fs");

extractFunction = (jsCode, regexp) => {
    const match = jsCode.match(regexp)
    if (!match && match.length <= 1) {
        return null;
    }
    let result = "";
    const dependencyMatchs = match[0].match(/([$a-zA-Z0-9]+\.[$a-zA-Z0-9]+)/g)
    const existDependencies = [];
    if (dependencyMatchs && dependencyMatchs.length >= 1) {
        for (let currentMatch of dependencyMatchs) {
            const varName = currentMatch.split('.')[0];
            if (existDependencies.includes(varName)) {
                continue
            }
            if (!/^[$A-Z]+$/.test(varName)) {
                continue
            }
            let reg = "var (\$)?" + varName + "={(.|\\n)*?};"
            const varNameMatch = jsCode.match(new RegExp(reg), 'ig');
            if (varNameMatch && varNameMatch.length >= 1) {
                result += varNameMatch[0] + "\n";
            }
            existDependencies.push(varName);
        }
    }
    result += `\n${match[0]}`;
    console.log(result);
    return eval(result);
}

const fileContent = fs.readFileSync('base.js');

const result = extractFunction(fileContent.toString(), /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{a=a\.split\(""\).*};/)
console.log(result('adoidjaijdioawjiodjaaa'))

const result2 = extractFunction(fileContent.toString(), /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{var b=a\.split\(""\)[\s\S]*?};/)
console.log(result2("dwjaiodjaiowidwa"));
