Skip to content

Commit 00bdb72

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 Backport-PR-URL: #46425 Reviewed-By: Geoffrey Booth <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]>
1 parent a3b0f4c commit 00bdb72

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

‎lib/internal/util.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,24 @@ function isArrayBufferDetached(value){
691691
returnfalse;
692692
}
693693

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+
functiongetLazy(initializer){
701+
letvalue;
702+
letinitialized=false;
703+
returnfunction(){
704+
if(initialized===false){
705+
value=initializer();
706+
initialized=true;
707+
}
708+
returnvalue;
709+
};
710+
}
711+
694712
// Setup user-facing NODE_V8_COVERAGE environment variable that writes
695713
// ScriptCoverage objects to a specified directory.
696714
functionsetupCoverageHooks(dir){
@@ -713,6 +731,7 @@ function setupCoverageHooks(dir){
713731
}
714732

715733
module.exports={
734+
getLazy,
716735
assertCrypto,
717736
cachedResult,
718737
convertToValidSignal,

0 commit comments

Comments
(0)