From 07559f72517214649d9146c4aaad60bb3317b9bf Mon Sep 17 00:00:00 2001 From: Justin Halsall Date: Thu, 2 Nov 2023 15:11:00 +0100 Subject: [PATCH] Parallelize getDataUriMapping --- lib/image.js | 39 +++++++++++++++------------------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/lib/image.js b/lib/image.js index 0f420e8..09aea7a 100644 --- a/lib/image.js +++ b/lib/image.js @@ -27,13 +27,6 @@ function encodeSvg(content) { ); } -async function reduceAsync(array = [], reducer = (r) => r, initial) { - for (const index of array.keys()) { - initial = await reducer(initial, array[index]); /* eslint-disable-line no-await-in-loop */ - } - - return initial; -} async function assertSize(resource, maxFileSize, throwError = true) { const {mime, contents = ''} = resource || {}; @@ -77,24 +70,22 @@ async function resolve(filepath, {assetPaths, maxFileSize, largeFileCallback, re } } -function getDataUriMapping(urls = [], options = {}) { - return reduceAsync( - [...new Set(urls)], - async (result, url) => { - const file = await resolve(url, options); - if (file && file.mime && /image/.test(file.mime)) { - result[url] = await getDataUri(file, options); - } else if (options.largeFileCallback) { - const largeFile = await resolve(url, {...options, maxFileSize: 0}); - if (largeFile && largeFile.mime && /image/.test(largeFile.mime)) { - result[url] = await options.largeFileCallback(largeFile); - } +async function getDataUriMapping(urls = [], options = {}) { + const uniqueUrls = [...new Set(urls)]; + const promises = uniqueUrls.map(async (url) => { + const file = await resolve(url, options); + if (file && file.mime && /image/.test(file.mime)) { + return [url, await getDataUri(file, options)]; + } else if (options.largeFileCallback) { + const largeFile = await resolve(url, {...options, maxFileSize: 0}); + if (largeFile && largeFile.mime && /image/.test(largeFile.mime)) { + return [url, await options.largeFileCallback(largeFile)]; } - - return result; - }, - {} - ); + } + return [url, null]; + }); + const results = await Promise.all(promises); + return Object.fromEntries(results); } module.exports.getDataUriMapping = getDataUriMapping;