is that really a good idea?
is that really a good idea?
function make_counter() {
var i = 0;
return (function() {
return i++;
});
}
var blah = make_counter();
every time you call `blah()` now, it will return the next number in the series, but there's no way for anywhere else in the application to modify `i`. This can be useful as an iterator, so giving you effectively the same as `yield`-ish generators in python.Purity is pretty awesome. I really like conceptual Haskell (actual real Haskell tends to become too abstract for my brain to remember important details when I come back to a project...).
The (sad) fact is that mutating a bit of state is actually often much faster, or a lot cleaner to read / understand than implementing a fully pure functional version. And by limiting access to state, you make sure you don't accidentally introduce dependencies.
Using closures like this, can end up being very similar to object-oriented code (in the best-case, strictly limited sense) whereby each area of concern in the code can only modify what you expect it to be able to modify, and you can be sure nowhere else in the code can access it.