Tail-call optimised recursive looping in JavaScript
Even though I should be carrying on building my game that is in on Wednesday, I had a spark of procrastination and built a JavaScript function to allow optimised tail-call recursion in JavaScript.
I based it on the Clojure Loop construct:
;;; Calculate Factorial of 5
(loop [n 5 acc 1]
(if (pos? n)
(recur (dec n) (* acc n))
acc))
The following is the equivalent loop call in JavaScript, using my new loop and recur functions:
loop({n: 5, acc: 1}, function (recur, data) {
if (data.n > 0) {
return recur({n: data.n - 1, acc: data.acc * data.n});
}
return data.acc;
});
Although it is a little nasty to have to use the data object, it does in fact work pretty well.
The implementation code is published on my GitHub at: JSLoop
Now back to my game development.