I am wondering what the best way is to check if an argument has already been called within a function.
Sudo code of what I want to do:
function returnArg(arg){
if(argHasbeenCalled){
return "foo";
}
else{
return arg;
}
}
My solution was:
var myArray = [];
function returnFoo(arg){
if(jQuery.inArray(arg, myArray) < 1){
return "Foo";
}
else {
return "bar";
}
newArray.push(arg);
}
Your code will return before storing the argument in your array.
You don't need to store the argument in your array unless you hit the else branch. So consider something like this:
var myArray = [];
function returnFoo(arg)
{
if (jQuery.inArray(arg, myArray) === -1)
{
return "Foo";
}
else
{
myArray.push(arg);
return "bar";
}
}
A simple solution would be:
// generic helper function
function rememberCalls(fn) {
var calledArgs = {};
return function(arg) {
if (!(arg in calledArgs)) {
calledArgs[arg] = fn(arg);
}
return calledArgs[arg];
}
}
// example
var addQuestionMark = rememberCalls(function(str) {
return str + '?';
});
addQuestionMark('What is your name'); // the function will be called
addQuestionMark('What is your name'); // the function will be skipped
I think what you want is called memoization . If you just want to know if the argument was ever processed, it's not exactly the same thing as you aren't interested in the result, but you can use a similar approach.
var myFn = (function (processedArgs) {
return function (arg) {
if (processedArgs[arg]) {
console.log('already processed');
//do something
return;
}
console.log('not processed');
//do something
processedArgs[arg] = true;
};
})({});
myFn(1); //not processed
myFn(1); //already processed
However, if arg
is an object, you will have to use some property of the object that makes it unique to generate a key. If that is not possible, you can store them in an array instead of using an object as a map and use array.indexOf(arg)
to see if the object is in the array.
You could also use an ObjectMap
. Unfortunately browsers still dont support Map
but the previously linked answer will show you how you could possibly implement one yourself.
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.