Skip to content

Instantly share code, notes, and snippets.

@njleonzhang
Last active August 27, 2016 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njleonzhang/438f7d7867aa41601aceb78437d5c7be to your computer and use it in GitHub Desktop.
Save njleonzhang/438f7d7867aa41601aceb78437d5c7be to your computer and use it in GitHub Desktop.
vue2.0 source code - cached
/**
 * 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。(每次输入,对应的输出一定是一致的)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment