From e4c98320d2551c4f2bf6ddcbf06eec54fab2858f Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Sun, 18 Jun 2023 00:42:16 +0300 Subject: [PATCH] refactor: code --- 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 6e15931..5809e67 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,7 @@ const { validate } = require("schema-utils"); const { throttleAll, + memoize, cssnanoMinify, cssoMinify, cleanCssMinify, @@ -151,31 +152,6 @@ const { minify: minifyWorker } = require("./minify"); const warningRegex = /\s.+:+([0-9]+):+([0-9]+)/; -/** - * @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 getSerializeJavascript = memoize(() => // eslint-disable-next-line global-require require("serialize-javascript") diff --git a/src/utils.js b/src/utils.js index d45f538..749355b 100644 --- a/src/utils.js +++ b/src/utils.js @@ -490,8 +490,34 @@ async function swcMinify(input, sourceMap, minimizerOptions) { }; } +/** + * @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, cssnanoMinify, cssoMinify, cleanCssMinify, diff --git a/types/utils.d.ts b/types/utils.d.ts index 0ab7728..de2846d 100644 --- a/types/utils.d.ts +++ b/types/utils.d.ts @@ -17,6 +17,12 @@ export type Postcss = import("postcss").Postcss; * @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 {RawSourceMap | undefined} sourceMap