-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreader-prefetch.js
More file actions
91 lines (79 loc) · 2.63 KB
/
Copy pathreader-prefetch.js
File metadata and controls
91 lines (79 loc) · 2.63 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Small priority scheduler shared by reader prefetch tasks.
*/
(function() {
'use strict';
if (window.MGR_READER_PREFETCH) return;
function create(options = {}) {
const maxConcurrent = Math.max(1, Number(options.maxConcurrent) || 2);
const run = typeof options.run === 'function' ? options.run : async function() {};
const shouldSkip = typeof options.shouldSkip === 'function' ? options.shouldSkip : function() { return false; };
const onError = typeof options.onError === 'function' ? options.onError : function() {};
const queue = [];
const queued = new Set();
const active = new Map();
function pump() {
while (active.size < maxConcurrent && queue.length > 0) {
const key = queue.shift();
queued.delete(key);
if (active.has(key) || shouldSkip(key)) continue;
const controller = new AbortController();
active.set(key, controller);
let task;
try {
task = run(key, controller.signal);
} catch (error) {
task = Promise.reject(error);
}
Promise.resolve(task)
.catch((error) => {
if (!controller.signal.aborted) onError(error, key);
})
.finally(() => {
active.delete(key);
pump();
});
}
}
function enqueue(keys, enqueueOptions = {}) {
if (!Array.isArray(keys) || keys.length === 0) return;
const additions = [];
for (const key of keys) {
if (queued.has(key) || active.has(key) || shouldSkip(key)) continue;
queued.add(key);
additions.push(key);
}
if (enqueueOptions.priority === true) {
queue.unshift(...additions);
} else {
queue.push(...additions);
}
pump();
}
function cancelExcept(keep) {
const predicate = typeof keep === 'function' ? keep : function(key) { return key === keep; };
for (let index = queue.length - 1; index >= 0; index--) {
if (predicate(queue[index])) continue;
queued.delete(queue[index]);
queue.splice(index, 1);
}
active.forEach((controller, key) => {
if (!predicate(key)) controller.abort('prefetch-cancel');
});
}
function clear() {
queue.length = 0;
queued.clear();
active.forEach((controller) => controller.abort('prefetch-clear'));
}
function snapshot() {
return {
queued: queue.slice(),
active: Array.from(active.keys()),
maxConcurrent
};
}
return Object.freeze({ enqueue, cancelExcept, clear, snapshot });
}
window.MGR_READER_PREFETCH = Object.freeze({ create });
})();