Skip to content

Commit ce5a518

Browse files
refactor: code (#569)
1 parent ef411cc commit ce5a518

File tree

3 files changed

+33
-25
lines changed

3 files changed

+33
-25
lines changed

src/index.js

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const { validate } = require("schema-utils");
55

66
const {
77
throttleAll,
8+
memoize,
89
terserMinify,
910
uglifyJsMinify,
1011
swcMinify,
@@ -149,31 +150,6 @@ const { minify } = require("./minify");
149150
* @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
150151
*/
151152

152-
/**
153-
* @template T
154-
* @param fn {(function(): any) | undefined}
155-
* @returns {function(): T}
156-
*/
157-
const memoize = (fn) => {
158-
let cache = false;
159-
/** @type {T} */
160-
let result;
161-
162-
return () => {
163-
if (cache) {
164-
return result;
165-
}
166-
result = /** @type {function(): any} */ (fn)();
167-
cache = true;
168-
// Allow to clean up memory for fn
169-
// and all dependent resources
170-
// eslint-disable-next-line no-undefined, no-param-reassign
171-
fn = undefined;
172-
173-
return result;
174-
};
175-
};
176-
177153
const getTraceMapping = memoize(() =>
178154
// eslint-disable-next-line global-require
179155
require("@jridgewell/trace-mapping")

src/utils.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,8 +755,34 @@ esbuildMinify.getMinimizerVersion = () => {
755755
return packageJson && packageJson.version;
756756
};
757757

758+
/**
759+
* @template T
760+
* @param fn {(function(): any) | undefined}
761+
* @returns {function(): T}
762+
*/
763+
function memoize(fn) {
764+
let cache = false;
765+
/** @type {T} */
766+
let result;
767+
768+
return () => {
769+
if (cache) {
770+
return result;
771+
}
772+
result = /** @type {function(): any} */ (fn)();
773+
cache = true;
774+
// Allow to clean up memory for fn
775+
// and all dependent resources
776+
// eslint-disable-next-line no-undefined, no-param-reassign
777+
fn = undefined;
778+
779+
return result;
780+
};
781+
}
782+
758783
module.exports = {
759784
throttleAll,
785+
memoize,
760786
terserMinify,
761787
uglifyJsMinify,
762788
swcMinify,

types/utils.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ export type ExtractedComments = Array<string>;
2727
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
2828
*/
2929
export function throttleAll<T>(limit: number, tasks: Task<T>[]): Promise<T[]>;
30+
/**
31+
* @template T
32+
* @param fn {(function(): any) | undefined}
33+
* @returns {function(): T}
34+
*/
35+
export function memoize<T>(fn: (() => any) | undefined): () => T;
3036
/**
3137
* @param {Input} input
3238
* @param {SourceMapInput | undefined} sourceMap

0 commit comments

Comments
 (0)