daily pastebin goal
0%
SHARE
TWEET

Untitled

a guest Mar 18th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Simple function */
  2.  
  3. const add = (n) => (n + 10);
  4.  
  5. const memoize = (fn) => {
  6.     let cache = {};
  7.   return (...args) => {
  8.     let n = args[0];
  9.     if (n in cache) {
  10.         console.log('Getting result from cache.')
  11.       return cache[n];
  12.     } else {
  13.         console.log('Calculating result');
  14.         let result = fn(n);
  15.       cache[n] = result;
  16.       return result;
  17.     }
  18.   }
  19. }
  20.  
  21. const memoizedAdd = memoize(add);
  22. console.log(memoizedAdd(5));
  23. console.log(memoizedAdd(6));
  24. console.log(memoizedAdd(5));
  25.  
  26. /* recursive */
  27. const factorial = memoize(
  28.     (x) => {
  29.         if (x === 0) return 1;
  30.     else return x * factorial(x - 1)
  31.     }
  32. )
  33.  
  34. console.log(factorial(5));
  35. console.log(factorial(6));
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top