0

Out of curiosity, I'd like to see if there's a better answer than what's below. How can I convert this:

def counter():
    ctr = 0
    def inner():
        ctr += 1
        return ctr
    return inner
counter = counter()

into this javascript equivalent?

counter = (function() {
    let ctr = 0;
    return function() {
        return ++ctr;
    } //inner anonymous func
})(); //outer func, called and forgotten, sort of.

The python above is fine, I was just curious if there was a faster/more readable way to do this.

To be clear, I don't want the outer factory function to be available after its called, and I want it to be called as soon as its defined. Think of it as a closure singleton. Thanks!

user1942362
  • 142
  • 2
  • 11
  • 1
    The subject of your question seems to ask for a Python solution, while the body of your question seems to ask for a JavaScript solution, and apparently you give the solution for both languages. What is the problem? – trincot Jun 02 '21 at 19:46
  • 1
    If you look for a code review for essentially working code, then this is more suited for [Code Review](https://codereview.stackexchange.com/) – trincot Jun 02 '21 at 19:47
  • The python above is fine? Did you test it? `ctr += 1` does not do what you think it does. – blhsing Jun 02 '21 at 20:08
  • "The python above is fine" no, it isn't. It will throw a `UnboundLocal` error. if you actually try to use `counter()` – juanpa.arrivillaga Jun 02 '21 at 20:21
  • Thanks for your comments. I gave the python solution I've been using, but wanted to know if there is a better way. The javascript example shows using anonymous functions, none of them have names. Maybe it is a code review thing, but not sure. Seemed to fit here, and I couldn't find answers to it. – user1942362 Jun 03 '21 at 02:26

0 Answers0