Hugo Almeida
Hugo Almeida

Reputation: 105

How can I convert an unnamed function to a named one?

I made the function below. Basically, if a player types /port and the name of another player the function returns true, I believe.

    mp.players.forEach(_player => {
        if(_player.name === name)
            return true;
    });

I want to name the function above so I can do something like:

if (functionName) [code]

So, how can I name the function above? Or is there any other way to check if it's true. I'm trying to list it on the try...catch statement below:

try {
        if (player.adminLevel < 8)  throw "Error 1";
        if (!targetPlayer) throw "Error 2";
        if (player.adminLevel <= targetAdminLevel) throw "Error 3";
        //AND THE NEW ONE HERE
        if (functionName) throw "Error 4";
    }

Upvotes: 1

Views: 70

Answers (2)

mangesh
mangesh

Reputation: 521

You have not created any function. forEach is a named function for Array prototype which you are invoking for your array. You can either directly write the forEach logic in your try block, or declare a named function and use it like below:

    function functionName(players, name){
            return players.some(_player => _player.name === name);
        };


    try {
           if (player.adminLevel < 8)  throw "Error 1";
           if (!targetPlayer) throw "Error 2";
           if (player.adminLevel <= targetAdminLevel) throw "Error 3";
           //AND THE NEW ONE HERE
           if (functionName(mp.players, player.name)) throw "Error 4";
     }

Upvotes: 0

John Wu
John Wu

Reputation: 52240

Just write it as a normal function, then pass the function name instead of the lambda expression.

function myFunction(player) {
    if(_player.name === name)
        return true;
}


mp.players.forEach(myFunction);

Now you can use myFunction elsewhere by its name... no "conversion" necessary.

Upvotes: 2

Related Questions