> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator/memoize/by-closure.md).

# memoize by closure

make a function "remember" its return values by closure.

[JS](/web/js.md) ⟩ [technique](/web/js/tech.md) ⟩ [memoize](/web/js/val/func/kind/higher/decorator/memoize.md) ⟩ by decorator

{% hint style="success" %} <mark style="color:orange;">**make**</mark> a [function](/web/js/val/func.md) "<mark style="color:yellow;">**remember**</mark>" its [return value](/web/js/val/func/return-value.md)s by using [closure](/web/js/val/func/closure.md).
{% endhint %}

{% tabs %}
{% tab title="💈範例" %}

* replit：[factorial (memoization by closure)](https://replit.com/@pegasusroe/factorial-memoization-by-closure#index.js)

```javascript
// ⭐ factorial wrapped in a closure (IIFE)
const factorial = (() => {

    // ⭐ internal cache for f
    const cache = {};

    return function f(x) {

        // base case:
        if (x < 2) return 1;
        // recursive case:
        if (!(x in cache)) cache[x] = x * f(x - 1);

        return cache[x];
    }

})();

factorial(6)    // 720
factorial(7)    // 5040
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] [YDKJS: Scope & Closures (v.2)](/web/master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2.md) ⟩ Ch. 6  (by IIFE, ie. closure)
* [ ] JS.info ⟩ [Decorators and forwarding, call/apply](https://javascript.info/call-apply-decorators) (by decorator)
* [ ] [\[演算法\] Fibonacci：善用 cache 和 Memoization 提升程式效能](https://pjchender.blogspot.com/2017/09/fibonacci-cache-memoization.html) (by parameter)
* [ ] Wictionary ⟩  [memoize](https://en.wiktionary.org/wiki/memoize) - to store (the result of a computation) so that it can be subsequently retrieved without repeating the computation.
  {% endtab %}

{% tab title="👥 相關" %}

* [memoize by decorator](/web/js/val/func/kind/higher/decorator/memoize/memoize-by-decorator.md)
  {% endtab %}
  {% endtabs %}
