/**
* Create a cached version of a pure function.
*/
export function cached (fn: Function): Function {
const cache = Object.create(null)
return function cachedFn (str: string): any {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
正如注释所言,是把pure function转成一个带cache的版本。
var b = cached(function(id) {
console.log('test');
return id
})
b("123")
==>
"test"
"123"
b("456")
==>
"test"
"456"
b("123")
==>
"123"
b("456")
==>
"456"
参数第一次被传入函数的时候,函数是执行的,第二次穿就不用执行了,参数被当做了key做了cache。对应的值直接回返回。 这样对于一些耗时的函数操作就避免了多次执行。
比如vue code里的:
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
还有一点很重要,就是这里做cahce的函数必须是pure function。(每次输入,对应的输出一定是一致的)