From 3dea88c74ee6233c3d8d7fa0d163ee80ba1a690d Mon Sep 17 00:00:00 2001 From: Pagan Gazzard Date: Fri, 11 Nov 2022 16:28:22 +0000 Subject: [PATCH] Remove some unnecessary usage of `.reduce` Change-type: patch --- src/compose/app.ts | 6 +-- src/compose/application-manager.ts | 60 ++++++++++++++++-------------- src/compose/images.ts | 39 +++++++++---------- src/config/backends/extra-uEnv.ts | 39 ++++++++++--------- src/config/backends/odmdata.ts | 14 +++---- src/device-state/preload.ts | 2 +- src/lib/system-info.ts | 6 +-- 7 files changed, 79 insertions(+), 87 deletions(-) diff --git a/src/compose/app.ts b/src/compose/app.ts index afce6299..e78233a5 100644 --- a/src/compose/app.ts +++ b/src/compose/app.ts @@ -444,10 +444,8 @@ export class App { // FIXME: We should add to the changingServices array, as we could emit several // kill steps for a service steps = steps.concat( - dependencies.reduce( - (acc, svc) => - acc.concat(this.generateKillStep(svc, changingServices)), - [] as CompositionStep[], + dependencies.flatMap((svc) => + this.generateKillStep(svc, changingServices), ), ); } else { diff --git a/src/compose/application-manager.ts b/src/compose/application-manager.ts index f8d5a153..5d2aa900 100644 --- a/src/compose/application-manager.ts +++ b/src/compose/application-manager.ts @@ -1081,37 +1081,41 @@ export async function getState() { .concat(stateFromServices); // Get the list of commits for all appIds from the database - const commitsForApp = ( - await Promise.all( - // Deduplicate appIds first - [...new Set(servicesToReport.map((svc) => svc.appId))].map( - async (appId) => ({ - [appId]: await commitStore.getCommitForApp(appId), - }), - ), - ) - ).reduce((commits, c) => ({ ...commits, ...c }), {}); + const commitsForApp: Dictionary = {}; + // Deduplicate appIds first + await Promise.all( + [...new Set(servicesToReport.map((svc) => svc.appId))].map( + async (appId) => { + commitsForApp[appId] = await commitStore.getCommitForApp(appId); + }, + ), + ); // Assemble the state of apps - return servicesToReport.reduce( - (apps, { appId, appUuid, commit, serviceName, createdAt, ...svc }) => ({ - ...apps, - [appUuid]: { - ...(apps[appUuid] ?? {}), - // Add the release_uuid if the commit has been stored in the database - ...(commitsForApp[appId] && { release_uuid: commitsForApp[appId] }), - releases: { - ...(apps[appUuid]?.releases ?? {}), - [commit]: { - ...(apps[appUuid]?.releases[commit] ?? {}), - services: { - ...(apps[appUuid]?.releases[commit]?.services ?? {}), - [serviceName]: svc, - }, + const state: { [appUuid: string]: AppState } = {}; + for (const { + appId, + appUuid, + commit, + serviceName, + createdAt, + ...svc + } of servicesToReport) { + state[appUuid] = { + ...state[appUuid], + // Add the release_uuid if the commit has been stored in the database + ...(commitsForApp[appId] && { release_uuid: commitsForApp[appId] }), + releases: { + ...state[appUuid]?.releases, + [commit]: { + ...state[appUuid]?.releases[commit], + services: { + ...state[appUuid]?.releases[commit]?.services, + [serviceName]: svc, }, }, }, - }), - {} as { [appUuid: string]: AppState }, - ); + }; + } + return state; } diff --git a/src/compose/images.ts b/src/compose/images.ts index 05256ea2..d7eee21a 100644 --- a/src/compose/images.ts +++ b/src/compose/images.ts @@ -597,12 +597,15 @@ export async function inspectByName(imageName: string) { // Run the queries in sequence, return the first one that matches or // the error from the last query - return await [inspectByURI, inspectByReference, inspectByDigest].reduce( - (promise, query) => promise.catch(() => query(imageName)), - Promise.reject( - 'Promise sequence in inspectByName is broken. This is a bug.', - ), - ); + let err; + for (const query of [inspectByURI, inspectByReference, inspectByDigest]) { + try { + return await query(imageName); + } catch ($err) { + err = $err; + } + } + throw err; } export async function cleanup() { @@ -681,10 +684,7 @@ async function removeImageIfNotNeeded(image: Image): Promise { digests: true, filters: { reference: [reference] }, }) - ).reduce( - (tagList, imgInfo) => tagList.concat(imgInfo.RepoTags || []), - [] as string[], - ); + ).flatMap((imgInfo) => imgInfo.RepoTags || []); reportEvent('start', { ...image, status: 'Deleting' }); logger.logSystemEvent(LogTypes.deleteImage, { image }); @@ -700,10 +700,9 @@ async function removeImageIfNotNeeded(image: Image): Promise { // Remove all matching tags in sequence // as removing in parallel causes some engine weirdness (see above) // this stops on the first error - await tags.reduce( - (promise, tag) => promise.then(() => docker.getImage(tag).remove()), - Promise.resolve(), - ); + for (const tag of tags) { + await docker.getImage(tag).remove(); + } // Check for any remaining digests. const digests = ( @@ -711,16 +710,12 @@ async function removeImageIfNotNeeded(image: Image): Promise { digests: true, filters: { reference: [reference] }, }) - ).reduce( - (digestList, imgInfo) => digestList.concat(imgInfo.RepoDigests || []), - [] as string[], - ); + ).flatMap((imgInfo) => imgInfo.RepoDigests || []); // Remove all remaining digests - await digests.reduce( - (promise, digest) => promise.then(() => docker.getImage(digest).remove()), - Promise.resolve(), - ); + for (const digest of digests) { + await docker.getImage(digest).remove(); + } // Mark the image as removed removed = true; diff --git a/src/config/backends/extra-uEnv.ts b/src/config/backends/extra-uEnv.ts index efde266d..73f88617 100644 --- a/src/config/backends/extra-uEnv.ts +++ b/src/config/backends/extra-uEnv.ts @@ -223,27 +223,26 @@ export class ExtraUEnv extends ConfigBackend { private static configToMap(configs: ConfigOptions): Map { // Reduce ConfigOptions into a Map that joins collections - return Object.entries(configs).reduce( - (configMap: Map, [configKey, configValue]) => { - const { key: ENTRY_KEY, collection: ENTRY_IS_COLLECTION } = - ExtraUEnv.supportedConfigs[configKey]; - // Check if we have to build the value for the entry - if (ENTRY_IS_COLLECTION) { - return configMap.set( - ENTRY_KEY, - ExtraUEnv.appendToCollection( - configMap.get(ENTRY_KEY), - configKey, - configValue, - ), - ); - } + const configMap = new Map(); + for (const [configKey, configValue] of Object.entries(configs)) { + const { key: ENTRY_KEY, collection: ENTRY_IS_COLLECTION } = + ExtraUEnv.supportedConfigs[configKey]; + // Check if we have to build the value for the entry + if (ENTRY_IS_COLLECTION) { + configMap.set( + ENTRY_KEY, + ExtraUEnv.appendToCollection( + configMap.get(ENTRY_KEY), + configKey, + configValue, + ), + ); + } else { // Set the value of this config - return configMap.set(ENTRY_KEY, `${configValue}`); - }, - // Start with empty Map - new Map(), - ); + configMap.set(ENTRY_KEY, `${configValue}`); + } + } + return configMap; } private static appendToCollection( diff --git a/src/config/backends/odmdata.ts b/src/config/backends/odmdata.ts index 8c6219f2..6c7a72ae 100644 --- a/src/config/backends/odmdata.ts +++ b/src/config/backends/odmdata.ts @@ -127,19 +127,15 @@ export class Odmdata extends ConfigBackend { ); } // Find the configuration given the optionsBuffer - const configIndex = this.CONFIG_BYTES.reduce( - (currentIndex: number, _config: number, index: number) => { - if ( + const configIndex = this.CONFIG_BYTES.findIndex( + (_config: number, index: number) => { + return ( this.CONFIG_BUFFER.readUInt8(index) === optionsBuffer.readUInt8(0) - ) { - return index; - } - return currentIndex; + ); }, - null, ); // Check if we found a configuration we support - if (configIndex === null) { + if (configIndex === -1) { log.error( `ODMDATA is set with an unsupported byte: 0x${optionsBuffer.readUInt8( 0, diff --git a/src/device-state/preload.ts b/src/device-state/preload.ts index 531f6527..088f8e0d 100644 --- a/src/device-state/preload.ts +++ b/src/device-state/preload.ts @@ -117,7 +117,7 @@ export async function loadTargetFromFile(appsPath: string): Promise { return imageFromService(svc); }); }) - .reduce((res, images) => res.concat(images), []); + .flat(); for (const image of imgs) { const name = imageManager.normalise(image.name); diff --git a/src/lib/system-info.ts b/src/lib/system-info.ts index 2d77eb2f..0c28bfd8 100644 --- a/src/lib/system-info.ts +++ b/src/lib/system-info.ts @@ -11,9 +11,9 @@ import { exec } from './fs-utils'; export async function getCpuUsage(): Promise { const cpuData = await systeminformation.currentLoad(); - const totalLoad = cpuData.cpus.reduce((load, cpuLoad) => { - return load + cpuLoad.load; - }, 0); + const totalLoad = _.sumBy(cpuData.cpus, ({ load }) => { + return load; + }); return Math.round(totalLoad / cpuData.cpus.length); }