Remove some unnecessary usage of .reduce

Change-type: patch
This commit is contained in:
Pagan Gazzard 2022-11-11 16:28:22 +00:00 committed by Page-
parent e64166a583
commit 3dea88c74e
7 changed files with 79 additions and 87 deletions

View File

@ -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 {

View File

@ -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<string | undefined> = {};
// 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;
}

View File

@ -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<void> {
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<void> {
// 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<void> {
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;

View File

@ -223,27 +223,26 @@ export class ExtraUEnv extends ConfigBackend {
private static configToMap(configs: ConfigOptions): Map<string, string> {
// Reduce ConfigOptions into a Map that joins collections
return Object.entries(configs).reduce(
(configMap: Map<string, string>, [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(

View File

@ -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,

View File

@ -117,7 +117,7 @@ export async function loadTargetFromFile(appsPath: string): Promise<boolean> {
return imageFromService(svc);
});
})
.reduce((res, images) => res.concat(images), []);
.flat();
for (const image of imgs) {
const name = imageManager.normalise(image.name);

View File

@ -11,9 +11,9 @@ import { exec } from './fs-utils';
export async function getCpuUsage(): Promise<number> {
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);
}