refactor: Prevent reduce calls

This commit is contained in:
Joachim Van Herwegen 2023-10-30 16:53:38 +01:00
parent 990184dbb5
commit 20d4a0c3af
12 changed files with 84 additions and 75 deletions

View File

@ -231,6 +231,7 @@ const configs = antfu(
}],
'unicorn/explicit-length-check': 'error',
'unicorn/new-for-builtins': 'error',
'unicorn/no-array-reduce': 'error',
'unicorn/no-for-loop': 'error',
'unicorn/no-invalid-remove-event-listener': 'error',
'unicorn/no-lonely-if': 'error',
@ -267,7 +268,6 @@ const configs = antfu(
'unicorn/require-number-to-fixed-digits-argument': 'error',
// Might want to enable these
'unicorn/no-array-reduce': 'off',
'unicorn/no-array-for-each': 'off',
'unicorn/no-await-expression-member': 'off',
'unicorn/no-negated-condition': 'off',

View File

@ -14,12 +14,13 @@ export class UnionCredentialsExtractor extends UnionHandler<CredentialsExtractor
public async combine(results: Credentials[]): Promise<Credentials> {
// Combine all the results into a single object
return results.reduce((result, credentials): Credentials => {
for (const key of Object.keys(credentials) as (keyof Credentials)[]) {
this.setValue(result, key, credentials[key]);
const credentials: Credentials = {};
for (const result of results) {
for (const key of Object.keys(result) as (keyof Credentials)[]) {
this.setValue(credentials, key, result[key]);
}
return result;
}, {});
}
return credentials;
}
/**

View File

@ -18,15 +18,16 @@ export class UnionPreferenceParser extends UnionHandler<PreferenceParser> {
throw new InternalServerError('Found multiple range values. This implies a misconfiguration.');
}
return results.reduce<RepresentationPreferences>((acc, val): RepresentationPreferences => {
for (const key of Object.keys(val) as (keyof RepresentationPreferences)[]) {
const preferences: RepresentationPreferences = {};
for (const result of results) {
for (const key of Object.keys(result) as (keyof RepresentationPreferences)[]) {
if (key === 'range') {
acc[key] = val[key];
preferences[key] = result[key];
} else {
acc[key] = { ...acc[key], ...val[key] };
preferences[key] = { ...preferences[key], ...result[key] };
}
}
return acc;
}, {});
}
return preferences;
}
}

View File

@ -97,10 +97,10 @@ export class RedirectingHttpHandler extends HttpHandler {
// Build redirect URL from regexp result
const { match, redirectPattern } = result;
const redirect = match.reduce(
(prev, param, index): string => prev.replace(`$${index}`, param),
redirectPattern,
);
let redirect = redirectPattern;
for (const [ i, element ] of match.entries()) {
redirect = redirect.replace(`$${i}`, element);
}
// Don't redirect if target is already correct
if (redirect === target) {

View File

@ -188,13 +188,13 @@ export class ChainedConverter extends RepresentationConverter {
* Will return undefined if there are no matches.
*/
private findBest(paths: ConversionPath[]): ConversionPath | undefined {
// Need to use null instead of undefined so `reduce` doesn't take the first element of the array as `best`
return paths.reduce((best: ConversionPath | null, path): ConversionPath | null => {
let best: ConversionPath | undefined;
for (const path of paths) {
if (path.weight > 0 && !(best && best.weight >= path.weight)) {
return path;
best = path;
}
}
return best;
}, null) ?? undefined;
}
/**

View File

@ -113,20 +113,20 @@ export function getWeightedPreferences(types: ValuePreferences, preferred: Value
* Undefined if there is no match.
*/
export function getBestPreference(types: ValuePreferences, preferred: ValuePreferences): ValuePreference | undefined {
// Could also return the first entry of the above function but this is more efficient
const result = Object.entries(types).reduce((best, [ value, quality ]): ValuePreference => {
// Could also return the first entry of `getWeightedPreferences` but this is more efficient
let best: ValuePreference = { value: '', weight: 0 };
for (const [ value, quality ] of Object.entries(types)) {
if (best.weight >= quality) {
return best;
continue;
}
const weight = quality * getTypeWeight(value, preferred);
if (weight > best.weight) {
return { value, weight };
best = { value, weight };
}
}
return best;
}, { value: '', weight: 0 });
if (result.weight > 0) {
return result;
if (best.weight > 0) {
return best;
}
}

View File

@ -526,7 +526,11 @@ export class WrappedIndexedStorage<T extends IndexTypeCollection<T>> implements
indexResults.push(rootIds);
}
return indexResults.reduce((acc, ids): string[] => acc.filter((id): boolean => ids.includes(id)));
let indexedRoots: string[] = indexResults[0];
for (const ids of indexResults.slice(1)) {
indexedRoots = indexedRoots.filter((id): boolean => ids.includes(id));
}
return indexedRoots;
}
/**
@ -581,9 +585,13 @@ export class WrappedIndexedStorage<T extends IndexTypeCollection<T>> implements
}
// For all keys that were not handled recursively: make sure that it matches the found objects
const remainingKeys = Object.keys(query).filter((key): boolean =>
key !== relation?.child.key || typeof query[key] === 'string');
return remainingKeys.reduce((acc, key): any[] => acc.filter((obj): boolean => obj[key] === query[key]), objs);
const remainingKeys = Object.keys(query).filter(
(key): boolean => key !== relation?.child.key || typeof query[key] === 'string',
);
for (const key of remainingKeys) {
objs = objs.filter((obj): boolean => obj[key] === query[key]);
}
return objs;
}
// --------------------------------- INDEX HELPERS ---------------------------------

View File

@ -71,17 +71,16 @@ export class FileSizeReporter implements SizeReporter<string> {
const childFiles = await fsPromises.readdir(fileLocation);
const rootFilePathLength = trimTrailingSlashes(this.rootFilePath).length;
return await childFiles.reduce(async(acc: Promise<number>, current): Promise<number> => {
let totalSize = stat.size;
for (const current of childFiles) {
const childFileLocation = normalizeFilePath(joinFilePath(fileLocation, current));
let result = await acc;
// Exclude internal files
if (!this.ignoreFolders.some((folder: RegExp): boolean =>
folder.test(childFileLocation.slice(rootFilePathLength)))) {
result += await this.getTotalSize(childFileLocation);
}
return result;
}, Promise.resolve(stat.size));
totalSize += await this.getTotalSize(childFileLocation);
}
}
return totalSize;
}
}

View File

@ -58,9 +58,10 @@ export class ContentType {
* @returns The value string, including parameters, if present.
*/
public toHeaderValueString(): string {
return Object.entries(this.parameters)
const parameterStrings = Object.entries(this.parameters)
.sort((entry1, entry2): number => entry1[0].localeCompare(entry2[0]))
.reduce((acc, entry): string => `${acc}; ${entry[0]}=${entry[1]}`, this.value);
.map(([ key, value ]): string => `${key}=${value}`);
return [ this.value, ...parameterStrings ].join('; ');
}
}

View File

@ -111,7 +111,8 @@ function handleInvalidValue(message: string, strict: boolean): void | never {
*/
export function parseParameters(parameters: string[], replacements: Record<string, string>, strict = false):
{ name: string; value: string }[] {
return parameters.reduce<{ name: string; value: string }[]>((acc, param): { name: string; value: string }[] => {
const parsed: { name: string; value: string }[] = [];
for (const param of parameters) {
const [ name, rawValue ] = param.split('=').map((str): string => str.trim());
// Test replaced string for easier check
@ -120,7 +121,7 @@ export function parseParameters(parameters: string[], replacements: Record<strin
if (!(TOKEN.test(name) && (!rawValue || /^"\d+"$/u.test(rawValue) || TOKEN.test(rawValue)))) {
handleInvalidValue(`Invalid parameter value: ${name}=${replacements[rawValue] || rawValue} ` +
`does not match (token ( "=" ( token / quoted-string ))?). `, strict);
return acc;
continue;
}
let value = rawValue;
@ -128,9 +129,9 @@ export function parseParameters(parameters: string[], replacements: Record<strin
value = replacements[rawValue];
}
acc.push({ name, value });
return acc;
}, []);
parsed.push({ name, value });
}
return parsed;
}
// eslint-disable-next-line jsdoc/require-returns-check
@ -239,17 +240,15 @@ export function parseAccept(input: string, strict = false): Accept[] {
// Quoted strings could prevent split from having correct results
const { result, replacements } = transformQuotedStrings(input);
return splitAndClean(result)
.reduce<Accept[]>((acc, part): Accept[] => {
const accepts: Accept[] = [];
for (const part of splitAndClean(result)) {
const partOrUndef = parseAcceptPart(part, replacements, strict);
if (partOrUndef !== undefined) {
acc.push(partOrUndef);
accepts.push(partOrUndef);
}
return acc;
}, [])
.sort((left, right): number => right.weight - left.weight);
}
return accepts.sort((left, right): number => right.weight - left.weight);
}
/**
@ -384,14 +383,11 @@ export function parseContentType(input: string): ContentType {
throw new BadRequestHttpError(`Invalid content-type: ${value} does not match ( token "/" token )`);
}
return parseParameters(params, replacements)
.reduce<ContentType>(
(prev, cur): ContentType => {
prev.parameters[cur.name] = cur.value;
return prev;
},
new ContentType(value),
);
const contentType = new ContentType(value);
for (const param of parseParameters(params, replacements)) {
contentType.parameters[param.name] = param.value;
}
return contentType;
}
/**

View File

@ -37,12 +37,13 @@ export async function parseQuads(readable: Guarded<Readable>, options: ParserOpt
* @returns A new array containing the unique quads.
*/
export function uniqueQuads(quads: Quad[]): Quad[] {
return quads.reduce<Quad[]>((result, quad): Quad[] => {
if (!result.some((item): boolean => quad.equals(item))) {
result.push(quad);
const uniques: Quad[] = [];
for (const quad of quads) {
if (!uniques.some((item): boolean => quad.equals(item))) {
uniques.push(quad);
}
return result;
}, []);
}
return uniques;
}
/**

View File

@ -34,12 +34,14 @@ export function errorTermsToMetadata(terms: Dict<string>, metadata?: Representat
* @param metadata - Metadata to extract the terms from.
*/
export function extractErrorTerms(metadata: RepresentationMetadata): Dict<string> {
return metadata.quads()
.filter((quad): boolean => quad.predicate.value.startsWith(SOLID_ERROR_TERM.namespace))
.reduce<NodeJS.Dict<string>>((acc, quad): Dict<string> => {
acc[quad.predicate.value.slice(SOLID_ERROR_TERM.namespace.length)] = quad.object.value;
return acc;
}, {});
const errorQuads = metadata.quads()
.filter((quad): boolean => quad.predicate.value.startsWith(SOLID_ERROR_TERM.namespace));
const errorTerms: Dict<string> = {};
for (const quad of errorQuads) {
errorTerms[quad.predicate.value.slice(SOLID_ERROR_TERM.namespace.length)] = quad.object.value;
}
return errorTerms;
}
/**