0

I'm not sure if what I am trying to do is impossible or not.

Consider this function:

function p(num) {
    if (!num) num = 1;
    return p.bind(null, num + 1);
}

if you call p(), inside the function num = 1, if you call p()(), num = 2 and so on. But, there is no way to actually return or obtain num from p because it always returns a bound copy of itself with the number trapped in its unexecutable closure.

Anyway, I'm curious (a) if there is a way to pull the argument out of the bound function, or (b) there is another way to count in this fashion.

Christopher Reid
  • 4,318
  • 3
  • 35
  • 74
  • How about returning an `object` ?.. `return {num:num,function:p.bind(null, num + 1)}` – Rayon May 24 '16 at 04:38
  • 2
    Have a look at [this very similar question](http://stackoverflow.com/a/18067040/1048572) – Bergi May 24 '16 at 04:39
  • @Bergi Wow, that is such a smart solution. I was going to do something weird with generators. – Joe Thomas May 24 '16 at 05:53
  • @AllTheTime, how about you tell us what you're actually trying to do with it? Show us another piece of code that would use this. I bet there's a better design. – Mulan May 25 '16 at 08:27

1 Answers1

0

I have two answers depending on what you want. If you simply want something "imperative" and "stateful":

    function p() {
      if (!p.num) p.num = 0;
      p.num = 1 + p.num;
      return p;
    }

    p();
    p.num; // 1
    p();
    p.num; // 2
    p()();
    p.num; // 4
    p()()();
    p.num; // 7

Or if you want it to be "stateless":

    function p() {
      p.num = 0;
      function gen_next(prev) {
        function next() {
          return gen_next(next);
        }
        next.num = prev.num + 1;
        return next;
      }
      return gen_next(p);
    }

    p().num; // 1
    p()().num; // 2
    p()()().num; // 3
    p()().num; // still 2
    p().num; // still 1
FPstudent
  • 831
  • 5
  • 9