解析js字符串

myEval

export const evalExp = /[!\&\|\+\-\*\%=\/<\>\^\(\)\~\:\?\;]/g;
export function myEval(originString: string, context: any) {
    if (!context) return;
    let bindKey = originString;
    bindKey = bindKey.replace(evalExp, " ");
    let bindKeys = bindKey
        .split(" ")
        .map(s => s.trim())
        .filter(e => !!e)
        .filter(e => {
            if (/^['"`]/.test(e)) {
                return false;
            }

            // 过滤布尔值
            if (e === "true" || e === "false") {
                return false;
            }

            // 过滤number
            if (!isNaN(+e)) {
                return false;
            }
            return true;
        });
    let args = bindKeys.map(s => {
        if (/\./.test(s) && /\[|\]/g.test(s)) {
            let aindex = s.indexOf(".");
            let bindex = s.indexOf("[");
            let index = Math.min(aindex, bindex);
            let obj = s.substr(0, index);
            return obj;
        } else if (/\./.test(s)) {
            let aindex = s.indexOf(".");
            let obj = s.substr(0, aindex);
            return obj;
        } else if (/\[|\]/g.test(s)) {
            let bindex = s.indexOf("[");
            let obj = s.substr(0, bindex);
            return obj;
        }
        return s;
    });
    args = toArray(new Set(args));
    const newArgs: string[] = [];
    let datas = args.map((k) => {
        if (k in context) {
            newArgs.push(k)
            return context[k]
        }
    }).filter(e => !!e);

    if (!datas.length) return;
    let funbody = `return function(${newArgs.toString()}) {
       'use strict';
       ${originString};
    }`;
    return Function(funbody)()(...datas);
}

evalFun

export function evalFun(bindKey: string, data: any) {
    if (undefinedp(data)) return;
    try {
        const r = Function(`with(this){ return ${bindKey} }`).apply(data, arguments)
        return r === '' ? undefined : r;
    } catch (error) {

    }
}

setData

export function setData(key: string, newValue: any, contextData: ContextData) {
    if (!stringp(key)) return null;
    return Function(`return function(d) {
        with(this){
          ${key} = d;
        }
      }`)().call(contextData.store, newValue);
}
posted @ 2019-12-20 16:48  Ajanuw  阅读(1948)  评论(0编辑  收藏  举报