From 723b6f1f31c5981c2e56b410bf049c26fac99a8f Mon Sep 17 00:00:00 2001 From: Sergey Chernyshev Date: Thu, 25 Apr 2024 01:48:03 +0200 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 --- graal-nodejs/lib/internal/util.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/graal-nodejs/lib/internal/util.js b/graal-nodejs/lib/internal/util.js index 4d72783617d..be4e60051d8 100644 --- a/graal-nodejs/lib/internal/util.js +++ b/graal-nodejs/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,