Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. ```
  2. /**
  3. * Create a cached version of a pure function.
  4. */
  5. export function cached (fn: Function): Function {
  6. const cache = Object.create(null)
  7. return function cachedFn (str: string): any {
  8. const hit = cache[str]
  9. return hit || (cache[str] = fn(str))
  10. }
  11. }
  12. ```
  13. 正如注释所言,是把pure function转成一个带cache的版本。
  14.  
  15. ```
  16. var b = cached(function(id) {
  17. console.log('test');
  18. return id
  19. })
  20. ```
  21. ```
  22. b("123")
  23. ==>
  24. "test"
  25. "123"
  26.  
  27. b("456")
  28. ==>
  29. "test"
  30. "456"
  31.  
  32. b("123")
  33. ==>
  34. "123"
  35.  
  36. b("456")
  37. ==>
  38. "456"
  39. ```
  40.  
  41. 参数第一次被传入函数的时候,函数是执行的,第二次穿就不用执行了,参数被当做了key做了cache。对应的值直接回返回。
  42. 这样对于一些耗时的函数操作就避免了多次执行。
  43.  
  44. 比如vue code里的:
  45. ```
  46. const idToTemplate = cached(id => {
  47. const el = query(id)
  48. return el && el.innerHTML
  49. })
  50. ```
  51.  
  52. 还有一点很重要,就是这里做cahce的函数必须是pure function。(每次输入,对应的输出一定是一致的)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement