-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
142 lines (120 loc) · 2.69 KB
/
index.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
export function series(tasks, done) {
let size;
let key;
let keys;
let result;
let iterate;
let completed = 0;
const step = function(err, ...args) {
if (err) {
done(err, result);
return;
}
result[key] = args.length <= 2 ? args[0] : args;
if (++completed === size) {
return done(null, result);
}
iterate();
};
if (Array.isArray(tasks)) {
size = tasks.length;
result = Array(size);
iterate = function() {
key = completed;
tasks[completed](step);
};
} else if (tasks && typeof tasks === 'object') {
keys = Object.keys(tasks);
size = keys.length;
result = {};
iterate = function() {
key = keys[completed];
tasks[key](step);
};
} else {
return done(null);
}
if (!size) {
return done(null, result);
}
iterate();
}
export function parallel(tasks, done) {
const results = [];
let counter = 0;
tasks.forEach((callback, index) => {
callback((...args) => {
results[index] = args;
counter++;
if (counter === tasks.length) {
done(results);
}
});
});
}
export function debounce(func, wait, immediate) {
let timeout;
const fn = function(...args) {
const later = () => {
timeout = null;
if (!immediate) {
func.apply(this, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(this, args);
}
};
fn.cancel = function() {
clearTimeout(timeout);
};
return fn;
}
export function throttle(func, wait, immediate) {
let timeout = null;
const fn = function(...args) {
if (timeout === null) {
immediate && func.apply(this, args);
timeout = setTimeout(() => {
timeout = null;
(!immediate) && func.apply(this, args);
}, wait);
}
};
fn.cancel = function() {
clearTimeout(timeout);
};
return fn;
}
export function retry(func, opts = {}) {
const interval = opts.interval || 1000;
const maxInterval = opts.maxInterval || 30000;
const maxAttempts = opts.maxAttempts || 10;
const decay = opts.decay || 1.5;
let attempts = 0;
let attemptTimeout;
let stopped = false;
const attempt = function() {
const timeout = interval * Math.pow(decay, attempts);
attempts++;
attemptTimeout = setTimeout(() => {
func(err => {
if (err && !stopped) {
if (maxAttempts) {
attempts < maxAttempts && attempt();
} else {
attempt();
}
}
});
}, Math.min(timeout, maxInterval));
}
attempt();
return () => {
stopped = true;
clearTimeout(attemptTimeout);
}
}