sheepdog sheepdog - 2 months ago 17
Javascript Question

Can't enable tail call optimization in node v6.4.0

I wan't to play around with tail call optimization in node/es2015, but I keep getting

RangeError: Maximum call stack size exceeded
. So I tried a very simple test function:

function countTo(n, acc) {
if(n === 0) {
return acc;
}
return countTo(n - 1, acc + n);
}

console.log(countTo(100000 , 0))


and it still fails. I've tried adding
'use strict';
inside the function body and at the top of the file. I've tried using
--harmony
and
--harmony-tailcalls


The same function works as expected in racket:

#lang racket
(define count-to
(lambda (n acc)
(cond
((= n 0) acc)
(else (count-to (- n 1) (+ acc n))))))
(count-to 100000000 0)
; ~> 5000000050000000


Edit:



As @MatthieuLemoine suggested. It works in v6.5.0+ with
"use strict";
and either
--harmony
or
--harmony-tailcalls


Answer

Using node v6.5.0, the following works :

function countTo(n, acc) {
  'use strict';
  if(n === 0) {
    return acc;
  }
  return countTo(n - 1, acc + n);
}
console.log(countTo(100000 , 0));

Running with --harmony-tailcalls flag :

node --harmony-tailcalls tco.js