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/explicit-length-check': 'error',
'unicorn/new-for-builtins': 'error', 'unicorn/new-for-builtins': 'error',
'unicorn/no-array-reduce': 'error',
'unicorn/no-for-loop': 'error', 'unicorn/no-for-loop': 'error',
'unicorn/no-invalid-remove-event-listener': 'error', 'unicorn/no-invalid-remove-event-listener': 'error',
'unicorn/no-lonely-if': 'error', 'unicorn/no-lonely-if': 'error',
@ -267,7 +268,6 @@ const configs = antfu(
'unicorn/require-number-to-fixed-digits-argument': 'error', 'unicorn/require-number-to-fixed-digits-argument': 'error',
// Might want to enable these // Might want to enable these
'unicorn/no-array-reduce': 'off',
'unicorn/no-array-for-each': 'off', 'unicorn/no-array-for-each': 'off',
'unicorn/no-await-expression-member': 'off', 'unicorn/no-await-expression-member': 'off',
'unicorn/no-negated-condition': '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> { public async combine(results: Credentials[]): Promise<Credentials> {
// Combine all the results into a single object // Combine all the results into a single object
return results.reduce((result, credentials): Credentials => { const credentials: Credentials = {};
for (const key of Object.keys(credentials) as (keyof Credentials)[]) { for (const result of results) {
this.setValue(result, key, credentials[key]); 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.'); throw new InternalServerError('Found multiple range values. This implies a misconfiguration.');
} }
return results.reduce<RepresentationPreferences>((acc, val): RepresentationPreferences => { const preferences: RepresentationPreferences = {};
for (const key of Object.keys(val) as (keyof RepresentationPreferences)[]) { for (const result of results) {
for (const key of Object.keys(result) as (keyof RepresentationPreferences)[]) {
if (key === 'range') { if (key === 'range') {
acc[key] = val[key]; preferences[key] = result[key];
} else { } 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 // Build redirect URL from regexp result
const { match, redirectPattern } = result; const { match, redirectPattern } = result;
const redirect = match.reduce( let redirect = redirectPattern;
(prev, param, index): string => prev.replace(`$${index}`, param), for (const [ i, element ] of match.entries()) {
redirectPattern, redirect = redirect.replace(`$${i}`, element);
); }
// Don't redirect if target is already correct // Don't redirect if target is already correct
if (redirect === target) { if (redirect === target) {

View File

@ -188,13 +188,13 @@ export class ChainedConverter extends RepresentationConverter {
* Will return undefined if there are no matches. * Will return undefined if there are no matches.
*/ */
private findBest(paths: ConversionPath[]): ConversionPath | undefined { 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` let best: ConversionPath | undefined;
return paths.reduce((best: ConversionPath | null, path): ConversionPath | null => { for (const path of paths) {
if (path.weight > 0 && !(best && best.weight >= path.weight)) { if (path.weight > 0 && !(best && best.weight >= path.weight)) {
return path; best = path;
}
} }
return best; return best;
}, null) ?? undefined;
} }
/** /**

View File

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

View File

@ -526,7 +526,11 @@ export class WrappedIndexedStorage<T extends IndexTypeCollection<T>> implements
indexResults.push(rootIds); 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 // For all keys that were not handled recursively: make sure that it matches the found objects
const remainingKeys = Object.keys(query).filter((key): boolean => const remainingKeys = Object.keys(query).filter(
key !== relation?.child.key || typeof query[key] === 'string'); (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); );
for (const key of remainingKeys) {
objs = objs.filter((obj): boolean => obj[key] === query[key]);
}
return objs;
} }
// --------------------------------- INDEX HELPERS --------------------------------- // --------------------------------- INDEX HELPERS ---------------------------------

View File

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

View File

@ -58,9 +58,10 @@ export class ContentType {
* @returns The value string, including parameters, if present. * @returns The value string, including parameters, if present.
*/ */
public toHeaderValueString(): string { public toHeaderValueString(): string {
return Object.entries(this.parameters) const parameterStrings = Object.entries(this.parameters)
.sort((entry1, entry2): number => entry1[0].localeCompare(entry2[0])) .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): export function parseParameters(parameters: string[], replacements: Record<string, string>, strict = false):
{ name: string; value: string }[] { { 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()); const [ name, rawValue ] = param.split('=').map((str): string => str.trim());
// Test replaced string for easier check // 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)))) { if (!(TOKEN.test(name) && (!rawValue || /^"\d+"$/u.test(rawValue) || TOKEN.test(rawValue)))) {
handleInvalidValue(`Invalid parameter value: ${name}=${replacements[rawValue] || rawValue} ` + handleInvalidValue(`Invalid parameter value: ${name}=${replacements[rawValue] || rawValue} ` +
`does not match (token ( "=" ( token / quoted-string ))?). `, strict); `does not match (token ( "=" ( token / quoted-string ))?). `, strict);
return acc; continue;
} }
let value = rawValue; let value = rawValue;
@ -128,9 +129,9 @@ export function parseParameters(parameters: string[], replacements: Record<strin
value = replacements[rawValue]; value = replacements[rawValue];
} }
acc.push({ name, value }); parsed.push({ name, value });
return acc; }
}, []); return parsed;
} }
// eslint-disable-next-line jsdoc/require-returns-check // 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 // Quoted strings could prevent split from having correct results
const { result, replacements } = transformQuotedStrings(input); const { result, replacements } = transformQuotedStrings(input);
return splitAndClean(result) const accepts: Accept[] = [];
.reduce<Accept[]>((acc, part): Accept[] => { for (const part of splitAndClean(result)) {
const partOrUndef = parseAcceptPart(part, replacements, strict); const partOrUndef = parseAcceptPart(part, replacements, strict);
if (partOrUndef !== undefined) { if (partOrUndef !== undefined) {
acc.push(partOrUndef); accepts.push(partOrUndef);
} }
}
return acc; return accepts.sort((left, right): number => right.weight - left.weight);
}, [])
.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 )`); throw new BadRequestHttpError(`Invalid content-type: ${value} does not match ( token "/" token )`);
} }
return parseParameters(params, replacements) const contentType = new ContentType(value);
.reduce<ContentType>( for (const param of parseParameters(params, replacements)) {
(prev, cur): ContentType => { contentType.parameters[param.name] = param.value;
prev.parameters[cur.name] = cur.value; }
return prev; return contentType;
},
new ContentType(value),
);
} }
/** /**

View File

@ -37,12 +37,13 @@ export async function parseQuads(readable: Guarded<Readable>, options: ParserOpt
* @returns A new array containing the unique quads. * @returns A new array containing the unique quads.
*/ */
export function uniqueQuads(quads: Quad[]): Quad[] { export function uniqueQuads(quads: Quad[]): Quad[] {
return quads.reduce<Quad[]>((result, quad): Quad[] => { const uniques: Quad[] = [];
if (!result.some((item): boolean => quad.equals(item))) { for (const quad of quads) {
result.push(quad); 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. * @param metadata - Metadata to extract the terms from.
*/ */
export function extractErrorTerms(metadata: RepresentationMetadata): Dict<string> { export function extractErrorTerms(metadata: RepresentationMetadata): Dict<string> {
return metadata.quads() const errorQuads = metadata.quads()
.filter((quad): boolean => quad.predicate.value.startsWith(SOLID_ERROR_TERM.namespace)) .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; const errorTerms: Dict<string> = {};
return acc; for (const quad of errorQuads) {
}, {}); errorTerms[quad.predicate.value.slice(SOLID_ERROR_TERM.namespace.length)] = quad.object.value;
}
return errorTerms;
} }
/** /**