如何在不使用模块作用域与包装函数的情况下简洁实现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
相关产品推荐
相关产品推荐

