Skip to content

Commit

Permalink
refactor: code (#569)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akait authored Jun 17, 2023
1 parent ef411cc commit ce5a518
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 25 deletions.
26 changes: 1 addition & 25 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { validate } = require("schema-utils");

const {
throttleAll,
memoize,
terserMinify,
uglifyJsMinify,
swcMinify,
Expand Down Expand Up @@ -149,31 +150,6 @@ const { minify } = require("./minify");
* @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} 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")
Expand Down
26 changes: 26 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions types/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export type ExtractedComments = Array<string>;
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
*/
export function throttleAll<T>(limit: number, tasks: Task<T>[]): Promise<T[]>;
/**
* @template T
* @param fn {(function(): any) | undefined}
* @returns {function(): T}
*/
export function memoize<T>(fn: (() => any) | undefined): () => T;
/**
* @param {Input} input
* @param {SourceMapInput | undefined} sourceMap
Expand Down

0 comments on commit ce5a518

Please sign in to comment.