Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 1 addition & 25 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { validate } = require("schema-utils");

const {
throttleAll,
memoize,
cssnanoMinify,
cssoMinify,
cleanCssMinify,
Expand Down Expand Up @@ -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")
Expand Down
26 changes: 26 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions types/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export type Postcss = import("postcss").Postcss;
* @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 {RawSourceMap | undefined} sourceMap
Expand Down