Skip to content

Commit 943852a

Browse files
joyeecheungtargos
authored andcommitted
lib: add getLazy() method to internal/util
This patch adds a getLazy() method to facilitate initialize-once lazy loading in the internals. PR-URL: #45849 Reviewed-By: Geoffrey Booth <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]>
1 parent c6ab449 commit 943852a

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

lib/internal/util.js

+19
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,26 @@ function isArrayBufferDetached(value) {
694694
return false;
695695
}
696696

697+
/**
698+
* Helper function to lazy-load an initialize-once value.
699+
* @template T Return value of initializer
700+
* @param {()=>T} initializer Initializer of the lazily loaded value.
701+
* @returns {()=>T}
702+
*/
703+
function getLazy(initializer) {
704+
let value;
705+
let initialized = false;
706+
return function() {
707+
if (initialized === false) {
708+
value = initializer();
709+
initialized = true;
710+
}
711+
return value;
712+
};
713+
}
714+
697715
module.exports = {
716+
getLazy,
698717
assertCrypto,
699718
cachedResult,
700719
convertToValidSignal,

0 commit comments

Comments
 (0)