【问题标题】:How to excute a function only once for same argument如何为相同的参数只执行一次函数
【发布时间】:2021-12-19 06:51:35
【问题描述】:

我的函数调用如下:

await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID)

假设使用 matchID '1' 调用该函数,它应该被执行,但如果使用 matchId '1' 再次调用该函数(在我的情况下),它不应该被执行。但是,如果使用 id '2'(基本上是 id !== '1')调用它,它应该被执行。我不在乎外野手的争论。

【问题讨论】:

  • 您正在寻找的内容称为 memoisation。您会发现很多使用该搜索词的解决方案。

标签: javascript node.js function


【解决方案1】:

您可以在函数外部跟踪数组中所有传递的参数。当您调用该函数时,它将检查提供的参数是否在数组中。如果不是,请调用该函数并将参数插入到数组中。如果参数已经在数组中,不要调用函数。

const suppliedMatchIDs = [];

function insertingMatchIdsInAllTeamPlayers(fieldersA, matchID) {
    if (suppliedMatchIDs.includes(matchID)) {
      return;
    } else {
      suppliedMatchIDs.push(matchID);
    }

    // Your function here
}

用于加速函数调用的caching参数的一般概念称为memoization

【讨论】:

  • 类似的方法对我有用。在函数内部,在底部,我将 matchId 参数保存在数据库中。
【解决方案2】:

使用closure 可以解决。

var insertingMatchIdsInAllTeamPlayers = (function() {
    var executed = [];
    return function(fieldersA,val) {
        if (executed.indexOf(val) == -1) {
            executed.push(val);
            console.log(val);
        }
    };
})();

insertingMatchIdsInAllTeamPlayers('',1); // console.log(1)
insertingMatchIdsInAllTeamPlayers('',1); // 
insertingMatchIdsInAllTeamPlayers('',2); // console.log(2)
insertingMatchIdsInAllTeamPlayers('',2); // 
insertingMatchIdsInAllTeamPlayers('',3); // console.log(3)

【讨论】:

    【解决方案3】:
    const matchIdFirstTimeOne = true
    if(matchId === 1 && matchIdFirstTimeOne) {
      await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID);
      matchIFirstTimeOne = false
    }
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2023-03-15
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多