Guest User

Untitled

a guest
Jan 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. const factorial = () => {
  2. const cached = {}
  3. return function(num) {
  4. console.time('NOT')
  5. console.time('CHACHED')
  6. console.log(cached)
  7. if (cached[num]) {
  8. console.timeEnd('CHACHED')
  9. return cached[num]
  10. }
  11. let result = 1
  12. for (let i = 1; i <= num; i++) {
  13. result = result * i
  14. }
  15. console.timeEnd('NOT')
  16. cached[num] = result
  17. return result
  18. }
  19. }
  20.  
  21. const memFact = factorial()
  22. console.log(memFact(50))
  23. console.log(memFact(50))
  24.  
  25. const memoize = fn => {
  26. const cache = {}
  27. return (...args) => {
  28. let result
  29. console.time('NOT')
  30. console.time('CHACHED')
  31. if (cache[args[0]]) {
  32. console.timeEnd('CHACHED')
  33. return cache[args[0]]
  34. }
  35. result = fn(...args)
  36. console.timeEnd('NOT')
  37. cache[args[0]] = result
  38. return result
  39. }
  40. }
  41.  
  42. const add = n => n + 10
  43. console.log('Simple call', add(3))
  44.  
  45. const memoizedAdd = memoize(add)
  46. console.log(memoizedAdd(3))
  47. console.log(memoizedAdd(3))
  48. console.log(memoizedAdd(4))
  49. console.log(memoizedAdd(4))
Add Comment
Please, Sign In to add comment