lib: add getLazy() method to internal/util

This patch adds a getLazy() method to facilitate initialize-once
lazy loading in the internals.

PR-URL: https://github.com/nodejs/node/pull/45849
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
This commit is contained in:
Joyee Cheung committed 2022-12-16 12:44:00 +01:00
1 parent 9d9bdfc693
commit 58762bbfe8
1 file changed
+19
+19
View File
@@ -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,