javascript - How to run corresponding function based on variable content?

WBOY
Release: 2023-03-02 13:40:02
Original
1347 people have browsed it

I wrote several functions funA(x), funB(x), funC(x), funD(x), funE(x), funF(x). Now I have a requirement, based on a certain parameter str , to implement different calculations. For example, when str='abc', x→funA(x)→funB(x)→funC(x)→y can be executed. When str'ace', x→funA(x)→funC( x)→funE(x)→y.

<code>function fun_abc(x)
{
    var a = funA(x);
    var b = funB(a);
    var c = funC(b);

    var y = c;
    
    return y;
}</code>
Copy after login
Copy after login

I know that I can write a switch to make a case based on str and jump to different fun_XXX(), but this is not flexible. My ultimate goal is to have an array with different function names written in order. When calling, input x, run the function corresponding to the first element in the array to the last function, and output the final result y.

Is there any other way to abbreviate it? Or can free combination be achieved, for example, directly executing a function with the same name based on a variable, like funstr='abc', running something like funstr(x) will execute function abc(x)?

js or php related syntax is acceptable.

Reply content:

I wrote several functions funA(x), funB(x), funC(x), funD(x), funE(x), funF(x). Now I have a requirement, based on a certain parameter str , to implement different calculations. For example, when str='abc', x→funA(x)→funB(x)→funC(x)→y can be executed. When str'ace', x→funA(x)→funC( x)→funE(x)→y.

<code>function fun_abc(x)
{
    var a = funA(x);
    var b = funB(a);
    var c = funC(b);

    var y = c;
    
    return y;
}</code>
Copy after login
Copy after login

I know that I can write a switch to make a case based on str and jump to different fun_XXX(), but this is not flexible. My ultimate goal is to have an array with different function names written in order. When calling, input x, run the function corresponding to the first element in the array to the last function, and output the final result y.

Is there any other way to abbreviate it? Or can free combination be achieved, for example, directly executing a function with the same name based on a variable, like funstr='abc', running something like funstr(x) will execute function abc(x)?

js or php related syntax is acceptable.

Let me give you an example, eval is too rude. . . Big brother, come and see me

<code>function run(str, param) {
  let handle = { a: a, b: b, c: c, d: d };
  return str.split('').reduce((res, name) => handle[name](res), param);

  function a(x) {
    return x + '1';
  }
  function b(x) {
    return x + '2';
  }
  function c(x) {
    return x + '3';
  }
  function d(x) {
    return x + '4';
  }
}

run('acb',0); // "0132"</code>
Copy after login

For example, similar ideas can be freely used

Improved on the basis of @ fish who don’t like tomatoes

  • Every time you call the run function, four functions and a map must be generated, which is relatively expensive. You can carry it outside run.

  • Use reduce instead of forEach

<code>const funcTable = { a, b, c, d }

function run(str, initialVal) {
  return str.split('').reduce((result, funcName) => funcTable[funcName](result), initialVal)
}

// 定义function a, function b...</code>
Copy after login

The simplest, eval
Troublesome {'abc': fabc}

The idea is very simple, I will post a sample code for both php and node

php version

<code>function funstr($str,$param){
    $len = strlen($str);
    for($i=0;$i<$len;$i++){
        $fun = 'fun'.strtoupper(substr($str,$i,1));
        if(function_exists($fun)){
            $param = $fun($param);
        }
    }
    return $param;
}

function funA($x) {
    return $x+1;
}

function funB($x) {
    return $x+2;
}

echo funstr('ab',0); // 输出3</code>
Copy after login

node version

<code>function funstr(str,x) {
  var len = str.length;
  for(var i=0; i<len; i++){
    var fun = 'fun'+ str.charAt(i).toUpperCase();
    x = eval(fun+'('+x+')');
  }
  return x;
}

function funA(x){
  return x+1;
}

function funB(x){
  return x+2;
}

console.log(funstr('ab',0));//输出3</code>
Copy after login

Put all the defined functions in an object, set the return value and call it;
var ab={

<code>    a:function(x){console.log(x);return 1},
    b:function(x){console.log(x);return 2},
    c:function(x){console.log(x);return 3},
    d:function(x){console.log(x);return 4},
}
function run(str,x){//str是定义的顺序,如acb;x是你要传的参数
    var b=x;
    var aa=str.split("")
    aa.forEach(function(x){
        ab[x](b);
        b=ab[x](b);
    })
    return b
}</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!