Skip to content

Commit 45d79e8

Browse files
committed
refactor(scraper): minor code cleanup as suggested in code review
- replace () => {return {...};} with () => ({...}) - remove commented-out code - move utils to their own files in /app/utils - create '#utils/' subpath imports for /app/utils
1 parent 8949123 commit 45d79e8

File tree

5 files changed

+158
-164
lines changed

5 files changed

+158
-164
lines changed

backend/app/utils/arrays.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
export function chunkArray<T>(array: T[], chunkSize: number): T[][] {
2+
const result = [];
3+
const input = Array.from(array);
4+
while (input.length > 0) {
5+
result.push(input.splice(0, chunkSize));
6+
}
7+
return result;
8+
}
9+
10+
export function zip<T1, T2>(a1: T1[], a2: T2[]): [T1, T2][] {
11+
const array1 = Array.from(a1);
12+
const array2 = Array.from(a2);
13+
const result: [T1, T2][] = [];
14+
while (array1.length > 0 && array2.length > 0) {
15+
const el1 = array1.shift() as T1;
16+
const el2 = array2.shift() as T2;
17+
result.push([el1, el2]);
18+
}
19+
return result;
20+
}

backend/app/utils/semaphore.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
export class Semaphore {
2+
capacity: number;
3+
#currentTasks: number;
4+
#waitingTasks: (() => void)[];
5+
6+
constructor(capacity: number) {
7+
this.capacity = capacity;
8+
this.#currentTasks = 0;
9+
this.#waitingTasks = [];
10+
}
11+
12+
public get currentTasks(): number {
13+
return this.#currentTasks;
14+
}
15+
16+
public async runTask<T>(task: () => Promise<T>): Promise<T> {
17+
// acquire the semaphore
18+
await this.acquire();
19+
try {
20+
// execute the task
21+
return await task();
22+
} finally {
23+
// don't forget to release
24+
this.release();
25+
}
26+
}
27+
28+
private acquire(): Promise<void> {
29+
// if we're under capacity, bump the count and resolve immediately
30+
if (this.capacity > this.#currentTasks) {
31+
this.#currentTasks += 1;
32+
return Promise.resolve();
33+
}
34+
// otherwise add ourselves to the queue
35+
return new Promise((resolve) => this.#waitingTasks.push(resolve));
36+
}
37+
38+
private release() {
39+
// try waking up the next task
40+
const nextTask = this.#waitingTasks.shift();
41+
if (nextTask === undefined) {
42+
// no task in queue, decrement task count
43+
this.#currentTasks -= 1;
44+
} else {
45+
// wake up the task
46+
nextTask();
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)