From ce5a518fb0cd8e7fb01a60bf6060e83adf6a17fe Mon Sep 17 00:00:00 2001 From: Alexander Akait <4567934+alexander-akait@users.noreply.github.com> Date: Sun, 18 Jun 2023 00:18:52 +0300 Subject: [PATCH] refactor: code (#569) --- src/index.js | 26 +------------------------- src/utils.js | 26 ++++++++++++++++++++++++++ types/utils.d.ts | 6 ++++++ 3 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/index.js b/src/index.js index 9d683f4..516d104 100644 --- a/src/index.js +++ b/src/index.js @@ -5,6 +5,7 @@ const { validate } = require("schema-utils"); const { throttleAll, + memoize, terserMinify, uglifyJsMinify, swcMinify, @@ -149,31 +150,6 @@ const { minify } = require("./minify"); * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation, options: MinimizerOptions } }} InternalPluginOptions */ -/** - * @template T - * @param fn {(function(): any) | undefined} - * @returns {function(): T} - */ -const memoize = (fn) => { - let cache = false; - /** @type {T} */ - let result; - - return () => { - if (cache) { - return result; - } - result = /** @type {function(): any} */ (fn)(); - cache = true; - // Allow to clean up memory for fn - // and all dependent resources - // eslint-disable-next-line no-undefined, no-param-reassign - fn = undefined; - - return result; - }; -}; - const getTraceMapping = memoize(() => // eslint-disable-next-line global-require require("@jridgewell/trace-mapping") diff --git a/src/utils.js b/src/utils.js index 55ebcea..28f0bb4 100644 --- a/src/utils.js +++ b/src/utils.js @@ -755,8 +755,34 @@ esbuildMinify.getMinimizerVersion = () => { return packageJson && packageJson.version; }; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +function memoize(fn) { + let cache = false; + /** @type {T} */ + let result; + + return () => { + if (cache) { + return result; + } + result = /** @type {function(): any} */ (fn)(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + // eslint-disable-next-line no-undefined, no-param-reassign + fn = undefined; + + return result; + }; +} + module.exports = { throttleAll, + memoize, terserMinify, uglifyJsMinify, swcMinify, diff --git a/types/utils.d.ts b/types/utils.d.ts index 5e0196e..a654e91 100644 --- a/types/utils.d.ts +++ b/types/utils.d.ts @@ -27,6 +27,12 @@ export type ExtractedComments = Array; * @returns {Promise} A promise that fulfills to an array of the results */ export function throttleAll(limit: number, tasks: Task[]): Promise; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +export function memoize(fn: (() => any) | undefined): () => T; /** * @param {Input} input * @param {SourceMapInput | undefined} sourceMap