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.
- This technique should guarantee that
emailServer.send(...)
will be called only once. How does it do so? How does the state ofhasRun
get saved? - Is there any use to creating a function which returns
f()
insideonceOnly(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.