I took this code from the Functional Programming with JavaScript Using EcmaScript 6 book.
This is how the code works. Calling doPayment()
multiple times don't execute the input arrow function () => { say("Payment Done") }
due to the internal variable done
is set to true
in the first run.
But my understand is that when doPayment()
is called every time, the variable done
will be initialized with false
every time, so the internal arrow function will run every time.
How is it working?
function say(v)
{
document.querySelector('#out').innerHTML += v + "</br>";
}
const once = fn => {
let done = false;
return function() {
return done ? undefined : ((done = true), fn.apply(this, arguments));
}
}
var doPayment = once(() => {
say("Payment Done");
});
doPayment();
doPayment();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<span id="out" style="font-family: roboto"></span>
</body>
</html>
--------- UPDATE --------------------
It's so discouraging to see how a moderately complex problem like this one is asked to be closed because it is a duplicate of some other question.
Among all the answers, @Sylvester's answer is chosen as the right answer. I have also given my own explanation as the answer.