| 
									
										
										
										
											2018-12-21 19:02:37 +08:00
										 |  |  | /* | 
					
						
							|  |  |  | 	MIT License http://www.opensource.org/licenses/mit-license.php
 | 
					
						
							|  |  |  | */ | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | "use strict"; | 
					
						
							|  |  |  | 
 | 
					
						
							| 
									
										
										
										
											2019-10-02 14:54:21 +08:00
										 |  |  | /** @template T @typedef {function(): T} FunctionReturning */ | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | /** | 
					
						
							|  |  |  |  * @template T | 
					
						
							|  |  |  |  * @param {FunctionReturning<T>} fn memorized function | 
					
						
							|  |  |  |  * @returns {FunctionReturning<T>} new function | 
					
						
							|  |  |  |  */ | 
					
						
							| 
									
										
										
										
											2018-12-21 19:02:37 +08:00
										 |  |  | const memorize = fn => { | 
					
						
							|  |  |  | 	let memorized = false; | 
					
						
							| 
									
										
										
										
											2019-10-02 14:54:21 +08:00
										 |  |  | 	/** @type {T} */ | 
					
						
							| 
									
										
										
										
											2018-12-21 19:02:37 +08:00
										 |  |  | 	let result = undefined; | 
					
						
							|  |  |  | 	return () => { | 
					
						
							|  |  |  | 		if (memorized) { | 
					
						
							|  |  |  | 			return result; | 
					
						
							|  |  |  | 		} else { | 
					
						
							|  |  |  | 			result = fn(); | 
					
						
							|  |  |  | 			memorized = true; | 
					
						
							|  |  |  | 			// Allow to clean up memory for fn
 | 
					
						
							|  |  |  | 			// and all dependent resources
 | 
					
						
							|  |  |  | 			fn = undefined; | 
					
						
							|  |  |  | 			return result; | 
					
						
							|  |  |  | 		} | 
					
						
							|  |  |  | 	}; | 
					
						
							|  |  |  | }; | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | module.exports = memorize; |