Skip to content

Instantly share code, notes, and snippets.

@danmarz
Last active November 23, 2021 23:15
Show Gist options
  • Save danmarz/43a711c8fe60527b81ea153d9222f16f to your computer and use it in GitHub Desktop.
Save danmarz/43a711c8fe60527b81ea153d9222f16f to your computer and use it in GitHub Desktop.

Revisions

  1. danmarz revised this gist Nov 23, 2021. No changes.
  2. danmarz revised this gist Nov 23, 2021. No changes.
  3. danmarz revised this gist Nov 23, 2021. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion memoized-fibonacci-JSbench.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    ```js
    function fibonacci(n) {
    if (n <= 1) {
    return 1
    @@ -50,4 +51,5 @@ function memoizer(fun) {
    }

    const fibonacciMemoFunction = memoizer(fibonacci)
    const fibonacciMemoFunction2 = memoizer(memoizedFibonacci)
    const fibonacciMemoFunction2 = memoizer(memoizedFibonacci)
    ```
  4. danmarz created this gist Nov 23, 2021.
    53 changes: 53 additions & 0 deletions memoized-fibonacci-JSbench.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    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)