Skip to content

Commit

Permalink
lib: add getLazy() method to internal/util
Browse files Browse the repository at this point in the history
This patch adds a getLazy() method to facilitate initialize-once
lazy loading in the internals.

PR-URL: #45849
Backport-PR-URL: #46425
Reviewed-By: Geoffrey Booth <[email protected]>
Reviewed-By: Chengzhong Wu <[email protected]>
  • Loading branch information
joyeecheung authored and targos committed Nov 10, 2023
1 parent a3b0f4c commit 00bdb72
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,24 @@ function isArrayBufferDetached(value) {
return false;
}

/**
* Helper function to lazy-load an initialize-once value.
* @template T Return value of initializer
* @param {()=>T} initializer Initializer of the lazily loaded value.
* @returns {()=>T}
*/
function getLazy(initializer) {
let value;
let initialized = false;
return function() {
if (initialized === false) {
value = initializer();
initialized = true;
}
return value;
};
}

// Setup user-facing NODE_V8_COVERAGE environment variable that writes
// ScriptCoverage objects to a specified directory.
function setupCoverageHooks(dir) {
Expand All @@ -713,6 +731,7 @@ function setupCoverageHooks(dir) {
}

module.exports = {
getLazy,
assertCrypto,
cachedResult,
convertToValidSignal,
Expand Down

0 comments on commit 00bdb72

Please sign in to comment.