You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用模块作用域与包装函数的情况下简洁实现TypeScript函数记忆化?

不依赖包装函数的函数记忆化实现

我想要一种不依赖包装函数的函数记忆化方法,最初想到直接把函数对象本身作为缓存载体,写出了初始实现代码,但觉得里面有不少重复内容,希望能有更简洁、可读性更强的写法。之后我对代码做了优化,同时也尝试了基于包装函数和模块作用域的实现方案,但这并不是我想要的最终方案。

初始实现代码

function getDocumentRegistry() {
  const self = getDocumentRegistry
  if (self.documentRegistry) return self.documentRegistry
  return self.documentRegistry = ts.createDocumentRegistry()
}

function main() {
  const foo = getDocumentRegistry()
}

优化后的代码

function getDocumentRegistry() {
  const self = getDocumentRegistry
  return self.value ?? (self.value = ts.createDocumentRegistry())
}

基于包装函数和模块作用域的实现(非目标方案)

function memoize(fn) {
  return fn.value ?? (fn.value = fn())
}

function getDocumentRegistry() {
  return ts.createDocumentRegistry()
}

const getDocumentRegistryCached = memoize(getDocumentRegistry)

内容的提问来源于stack exchange,提问作者vaughan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:09:57