Skip to content

Commit

Permalink
refactor: code (#236)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akait committed Jun 18, 2023
1 parent 8a7542a commit 03c6274
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 @@ -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

0 comments on commit 03c6274

Please sign in to comment.