From 00bdb72b6ec20a4f9f8366378f49319b4805c2b7 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 14 Dec 2022 00:02:51 +0100 Subject: [PATCH] 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 Backport-PR-URL: https://github.com/nodejs/node/pull/46425 Reviewed-By: Geoffrey Booth Reviewed-By: Chengzhong Wu --- lib/internal/util.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/lib/internal/util.js b/lib/internal/util.js index 4d72783617dd03..be4e60051d8319 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -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) { @@ -713,6 +731,7 @@ function setupCoverageHooks(dir) { } module.exports = { + getLazy, assertCrypto, cachedResult, convertToValidSignal,