const isPositive = (n: number) => n > 0;
function fitsIn(dividend: number,
divisor: number,
count: number,
accum: number): number {
if (accum + divisor > dividend) {
return count;
}
return fitsIn(dividend, divisor, count + 1, accum + divisor);
}
function divide(dividend: number, divisor: number): number {
let timesFits = fitsIn(Math.abs(dividend), Math.abs(divisor), 0, 0);
return isPositive(dividend) === isPositive(divisor) ? timesFits : -timesFits;
}
console.log(divide(10, 3));
// 3
console.log(divide(-2147483648, -1));
// RangeError: Maximum call stack size exceeded
console.log(divide(10000, 1));
// RangeError: Maximum call stack size exceeded
I tried running this code with TypeScript 4.6.2 in Strict Mode and it caused the stack to overflow. The recursive call is at the end of the function and the accumulation is done inside the recursive function calls. Shouldn't this code be optimized for tail recursion? What should be changed to get tail recursion optimization to occur?