Whenever somebody post an article about recursion with JavaScript they tend to stop with a body-recursive solution.
Given that JavaScript runtimes don't tend to support tail call optimization (more generally last call optimization to support mutual recursion) there may seem to be little value in going through the extra step of transforming to a tail-recursive solution.
What's the equivalent of a tail-recursive solution in JavaScript?
A loop.
In my judgement ad hoc loops can get pretty messy. One way to clean things up is to force the solution through the
ad hoc loop -> body-recursion -> tail-recursion -> clean loop
transformation (for an an example of the last part see my comment here).
I'm going to guess that you find your version much easier to read.
I would call your version "statement-based" while my version is "expression-based".
In my experience concepts like recursion (the mindset if you will) come much easier when you start moving to a more expression-based style of thinking:
functions, just like expressions, produce a value (even if it is just undefined). Statements do not.
Becoming more aware of the tension between statements and expressions (or functions) makes it possible to adopt a more value-oriented approach where appropriate (I'd classify recursion as a value-oriented technique).
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Whenever somebody post an article about recursion with JavaScript they tend to stop with a body-recursive solution.
Given that JavaScript runtimes don't tend to support tail call optimization (more generally last call optimization to support mutual recursion) there may seem to be little value in going through the extra step of transforming to a tail-recursive solution.
What's the equivalent of a tail-recursive solution in JavaScript?
A loop.
In my judgement ad hoc loops can get pretty messy. One way to clean things up is to force the solution through the
ad hoc loop -> body-recursion -> tail-recursion -> clean loop
transformation (for an an example of the last part see my comment here).
The other thing — you close with this code
There's nothing wrong with it.
Compare this with my starting point:
I'm going to guess that you find your version much easier to read.
I would call your version "statement-based" while my version is "expression-based".
In my experience concepts like recursion (the mindset if you will) come much easier when you start moving to a more expression-based style of thinking:
undefined
). Statements do not.Becoming more aware of the tension between statements and expressions (or functions) makes it possible to adopt a more value-oriented approach where appropriate (I'd classify recursion as a value-oriented technique).