I am trying to understand functional programming and saw the following example:
function onceOnly(f) {
var hasRun = false;
return function() {
if(!hasRun){
hasRun = true;
return f();
}
}
}
// Call as many times as you like
var sendWelcomeEmail = onlyOnce(function() {
emailServer.send(...);
});
There are a few things that I do not understand about this.
emailServer.send(...) will be called only once. How does it do so? How does the state of hasRun get saved?f() inside onceOnly(f)? Why did we not simply do the following:function onceOnly(f) {
var hasRun = false;
if(!hasRun){
hasRun = true;
return f();
}
}
The source of this code can be found here
Thank you.
The aim of onlyOnce is to return a function, not calling a function. Your second example is calling the function and return the result of f.
Wherease, with the first implementation
//return a reference to an anonymous function
var sendWelcomeEmail = onlyOnce(...);
//you can use it to call after
sendWelcomeEmail();
Simply put a console.log() just before return f() you'll see the difference.
hasRun is first initiate with false. Once sendWelcomeEmail() is called, hasRun will be set to true. Since sendWelcomeEmail is referenced to an anonymous function, it is unique and exist in the memory, a second call to this same function will not trigger f() because hasRun is also uniquely referenced and got memorized.