GeezerVison is showing github.com — lib: add getLazy() method to internal/util · nodejs/node@00bdb72
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: lib/internal/util.js +19Lines changed: 19 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -691,6 +691,24 @@ function isArrayBufferDetached(value) { |
691 | 691 | return false; |
692 | 692 | } |
693 | 693 |
|
| 694 | +/** |
| 695 | + * Helper function to lazy-load an initialize-once value. |
| 696 | + * @template T Return value of initializer |
| 697 | + * @param {()=>T} initializer Initializer of the lazily loaded value. |
| 698 | + * @returns {()=>T} |
| 699 | + */ |
| 700 | +function getLazy(initializer) { |
| 701 | + let value; |
| 702 | + let initialized = false; |
| 703 | + return function() { |
| 704 | + if (initialized === false) { |
| 705 | + value = initializer(); |
| 706 | + initialized = true; |
| 707 | + } |
| 708 | + return value; |
| 709 | + }; |
| 710 | +} |
| 711 | + |
694 | 712 | // Setup user-facing NODE_V8_COVERAGE environment variable that writes |
695 | 713 | // ScriptCoverage objects to a specified directory. |
696 | 714 | function setupCoverageHooks(dir) { |
@@ -713,6 +731,7 @@ function setupCoverageHooks(dir) { |
713 | 731 | } |
714 | 732 |
|
715 | 733 | module.exports = { |
| 734 | + getLazy, |
716 | 735 | assertCrypto, |
717 | 736 | cachedResult, |
718 | 737 | convertToValidSignal, |
|