[Javascript] Trampolines & Tail call
Blog: https://www.geeksforgeeks.org/es6-trampoline-function/
Stackoverflow problem for recursion:
const sumBelow = (number, sum = 0) => (
number === 0
? sum
: sumBelow(number - 1, sum + number)
)
sumBelow(100000);
// Uncaught RangeError: Maximum call stack size exceeded
The recursive function keeps adding entries to the JavaScript engines call stack until there’s no more room, and then we get an error (if you want to read a bit more about how the call stack works, feel free to check out this article).
Tail calls
One way to avoid blowing up the call stack is to use proper tail calls — these were added in the ES2015 spec. In order to use proper tail calls (PTC), a function satisfy the following conditions:
- You must be in
use strict
mode. - The recursive function call must be in tail position — that is, it is the very last thing to be evaluated before the
return
statement. For a detailed overview of what constitutes tail position, there’s a really nice dive into that in in this post.
Trampolines
Idea of Trampolines is that: inside a function, call another function which returns your a function. We have a while loop to keep calling the return function until it is no longer a function type. This helps to reduce our callstack.
const trampoline = fn => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
Usage:
const sumBelowRec = (number, sum = 0) => (
number === 0
? sum
: () => sumBelowRec(number - 1, sum + number) // return a function
)
const sumBelow = trampoline(sumBelowRec)
sumBelow(100000)
// returns 5000050000 🎉🎉🎉
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-08-18 [SAA + SAP] 29. Disaster Recovery
2021-08-18 [SAA + SAP] 28. Monitoring
2020-08-18 [VSCode] Visually Organize Applications in VS Code with Window Color-Coding
2020-08-18 [VSCode] Create a sharable code snippet image with Polacode extension
2020-08-18 [Javascript] Build lodash.omitBy and lodash.pickBy with Object.fromEntries + Object.entry (isomorphism)
2018-08-18 [Maid] Write Tasks in Markdown with Maid
2018-08-18 [React] Preview and edit a component live with React Live