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
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
  • Loading branch information
joyeecheung authored and targos committed Jan 1, 2023
1 parent c6ab449 commit 943852a
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/internal/util.js
Expand Up @@ -694,7 +694,26 @@ 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;
};
}

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

0 comments on commit 943852a

Please sign in to comment.