Skip to content

Instantly share code, notes, and snippets.

@dan-dm
Last active November 23, 2021 23:15
Show Gist options
  • Save dan-dm/43a711c8fe60527b81ea153d9222f16f to your computer and use it in GitHub Desktop.
Save dan-dm/43a711c8fe60527b81ea153d9222f16f to your computer and use it in GitHub Desktop.
Memoization is an optimization technique that speeds up applications by storing the results of expensive function calls and returning the cached result when the same inputs occur again. Check it out -> https://jsbench.me/foktstl85t/1
function fibonacci(n) {
  if (n <= 1) {
    return 1
  }

  return fibonacci(n - 1) + fibonacci(n - 2);
}

function memoizedFibonacci(n, memo) {
  memo = memo || {}

  if (memo[n]) {
    return memo[n]
  }

  if (n <= 1) {
    return 1
  }
  
  return memo[n] = memoizedFibonacci(n - 1, memo) + memoizedFibonacci(n - 2, memo)
}

function memoizedFibonacci2(n, memo) {
  memo = memo || {}

  if (memo[n]) {
    return memo[n]
  }

  if (n <= 1) {
    return 1
  }
  
  return memo[n] = memoizedFibonacci2(n - 2, memo) + memoizedFibonacci2(n - 1, memo)
}

function memoizer(fun) {
  let cache = {}

  return function(n) {
    if (cache[n] != undefined ) {
      return cache[n]
    } else {
      let result = fun(n)
      cache[n] = result

      return result
    }
  }
}

const fibonacciMemoFunction = memoizer(fibonacci)
const fibonacciMemoFunction2 = memoizer(memoizedFibonacci)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment