简体   繁体   中英

Dynamicly defined function call inside module

There is a code, problem inside 'interpret': how to call any given function from 'func' inside, not just 'sum3'?

const sum = (...args) => {
    return args.reduce((prev, curr) => prev + curr)}

const defn = (functionName, args, body) => {
    let [func, ...params] = body;
    let result = `var ${functionName} = function(${args.join(',')}) { return ${func.name}(${params.join(',')})}`
    return result;
}

const interpret = (...code) => {
    let [dfStr, callString] = code;
    let [func, ...args] = callString;
    eval(dfStr[0](dfStr[1], dfStr[2], dfStr[3] ));
    return sum3.apply(this, args);
    }


const result = interpret(
    [defn, "sum3", ['a', 'b', 'c'], [sum, 'a', 'b', 'c']],
    ['sum3', 10, 20, 30]
)

Note that you eval the function definition but not the corresponding call,

Check this out:

 const sum = (...args) => { return args.reduce((prev, curr) => prev + curr) } const defn = (functionName, args, body) => { let [func, ...params] = body; let result = `var ${functionName} = function(${args.join(',')}) { return ${func.name}(${params.join(',')})}` return result; } const interpret = (...code) => { let [dfStr, callString] = code; let [func, ...args] = callString; eval(dfStr[0](dfStr[1], dfStr[2], dfStr[3])); return eval(`${func}.apply(this, args)`); } const result = interpret( [defn, "sum3", ['a', 'b', 'c'], [sum, 'a', 'b', 'c'] ], ['sum3', 10, 20, 30] ) console.log(result)

TBH I have no idea what you are trying to do but keep in mind that using eval is an evil practice. Maybe you can think of a cleaner solution to fit the purpose.

Update :

 const sum = (...args) => { return args.reduce((prev, curr) => prev + curr) } const defn = (functionName, args, body) => { let [func, ...params] = body; let result = `(${args.join(',')}) =>${func.name}(${params.join(',')})` return result; } const interpret = (...code) => { let [dfStr, callString] = code; let [func, ...args] = callString; return eval(dfStr.shift()(...dfStr)).apply(this, args) } const result = interpret( [defn, "sum3", ['a', 'b', 'c'], [sum, 'a', 'b', 'c'] ], ['sum3', 10, 20, 30] ) console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM