Home > Back-end >  How to excute a function only once for same argument
How to excute a function only once for same argument

Time:11-05

My function call is given below:

await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID)

Suppose the function is called with matchID '1', it should get executed, but if the function is called again with matchId '1'(It will in my case), it should not be executed. However, if it is called with id '2' (basically id !== '1'), it should be executed. I don't care for fieldersA argument.

CodePudding user response:

You could track all passed arguments in array outside of the function. When you call the function, it will check, if the supplied argument is in the array. If it's not, call the function and insert the argument into the array. If the argument is already in the array, don't call the function.

const suppliedMatchIDs = [];

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

    // Your function here
}

The general concept of caching arguments to speed up function calls is called memoization.

CodePudding user response:

const matchIdFirstTimeOne = true
if(matchId === 1 && matchIdFirstTimeOne) {
  await insertingMatchIdsInAllTeamPlayers(fieldersA, matchID);
  matchIFirstTimeOne = false
}

CodePudding user response:

Using closure could solve it.

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)
  • Related