From 943852ab83e26a7463d9a90b66fa49687def59ff 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 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 ce332aa9daa178..38002b421376ec 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -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,