-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex2.js
More file actions
43 lines (33 loc) · 940 Bytes
/
ex2.js
File metadata and controls
43 lines (33 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'use strict';
/*
Problem:
Implement `runTasks(tasks, mode)`.
Input:
- `tasks`: array of functions returning promises
- `mode`: "sequential" | "parallel"
Rules:
- sequential: await each task before starting the next one.
- parallel: start all tasks immediately, then await all.
Return:
- Promise resolving to array of results in task order.
Starter code is intentionally incorrect:
- It starts all tasks immediately in both modes.
*/
async function runTasks(tasks, mode) {
if (!Array.isArray(tasks)) {
throw new TypeError('tasks must be an array');
}
if (mode !== 'sequential' && mode !== 'parallel') {
throw new TypeError('mode must be "sequential" or "parallel"');
}
const started = tasks.map((task) => task());
if (mode === 'parallel') {
return Promise.all(started);
}
const results = [];
for (const p of started) {
results.push(await p);
}
return results;
}
module.exports = { runTasks };