UNPKG

604 BJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3*/
4
5"use strict";
6
7/** @template T @typedef {function(): T} FunctionReturning */
8
9/**
10 * @template T
11 * @param {FunctionReturning<T>} fn memorized function
12 * @returns {FunctionReturning<T>} new function
13 */
14const memoize = fn => {
15 let cache = false;
16 /** @type {T} */
17 let result = undefined;
18 return () => {
19 if (cache) {
20 return result;
21 } else {
22 result = fn();
23 cache = true;
24 // Allow to clean up memory for fn
25 // and all dependent resources
26 fn = undefined;
27 return result;
28 }
29 };
30};
31
32module.exports = memoize;