refactor(api): parameterize max iterations of updateObject util

This commit is contained in:
Pujit Mehrotra
2024-10-23 14:41:50 -04:00
parent eb7bdb6a85
commit 57fdcf3e60
2 changed files with 12 additions and 3 deletions

View File

@@ -550,9 +550,9 @@ export class NotificationsService {
private async listFilesInFolder(folderPath: string, sortFn?: SortFn<Stats>): Promise<string[]> {
sortFn ??= (fileA, fileB) => fileB.birthtimeMs - fileA.birthtimeMs; // latest first
const contents = await readdir(folderPath);
// pre-map each file's stats to avoid excess calls during sorting
return contents
.map((content) => {
// pre-map each file's stats to avoid excess calls during sorting
const path = join(folderPath, content);
return { path, stats: statSync(path) };
})

View File

@@ -62,6 +62,10 @@ export async function batchProcess<Input, T>(items: Input[], action: (id: Input)
};
}
type IterationOptions = {
maxIterations?: number;
};
/**
* Traverses an object and its nested objects, passing each one to a callback function.
*
@@ -72,11 +76,16 @@ export async function batchProcess<Input, T>(items: Input[], action: (id: Input)
* @param obj - The object to be traversed and modified.
* @param modifier - A callback function, taking an object. Modifications should happen in place.
*/
export function updateObject(obj: object, modifier: (currentObj: object) => void) {
export function updateObject(
obj: object,
modifier: (currentObj: object) => void,
opts: IterationOptions = {}
) {
const stack = [obj];
let iterations = 0;
const { maxIterations = 100 } = opts;
// Prevent infinite loops
while (stack.length > 0 && iterations < 100) {
while (stack.length > 0 && iterations < maxIterations) {
const current = stack.pop();
if (current && typeof current === 'object') {