-
Notifications
You must be signed in to change notification settings - Fork 7
/
utility.js
403 lines (378 loc) · 13.5 KB
/
utility.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
export {
createDebounced,
createThrottled,
throttledWithLast,
chainPromiseNTimes,
chainPromises,
forceThrottlePromiseCreator,
throttlePromiseCreator,
throttlePromiseCreatorSelfClean,
somePromisesParallel,
chainRequestAnimationFrame,
decorateForceSequential,
doNTimes,
timeFunction,
timePromise,
memoizeAsStrings,
createTemplateTag,
bytesLengthFromString,
assignSelected,
};
const timeDefault = 150;
/** creates a function that is de-bounced,
calling it, will eventually execute it, when you stop calling it
useful for scroll events, resize, search etc
the returned function always returns undefined */
const createDebounced = function (functionToDebounce, waitTime = timeDefault) {
let timeOutId = 0;
return function (...args) {
if (timeOutId !== 0) {
clearTimeout(timeOutId);
timeOutId = 0;
}
timeOutId = setTimeout(function () {
timeOutId = 0;
functionToDebounce(...args);
}, waitTime);
};
};
/** creates a function that is throttled,
calling it once will execute it immediately
calling it very often during a period less than minimumTimeSpace will only execute it once
the returned function always returns undefined */
const createThrottled = function (functionToThrottle, minimumTimeSpace = timeDefault) {
let lastTime = Number.MIN_SAFE_INTEGER;
return function (...args) {
const now = Date.now();
if (minimumTimeSpace > now - lastTime) {
return;
}
lastTime = now;
functionToThrottle(...args);
};
};
/** creates a function that is throttled,
calling it once will execute it immediately
calling it very often during a period less than minimumTimeSpace will only execute it twice:
the first and last call
The last call is always eventually executed
the returned function always returns undefined */
const throttledWithLast = function (functionToThrottle, minimumTimeSpace = timeDefault) {
let timeOutId = 0;
let lastTime = Number.MIN_SAFE_INTEGER;
return function (...args) {
const now = Date.now();
const timeAlreadyWaited = now - lastTime;
if (timeOutId !== 0) {
clearTimeout(timeOutId);
timeOutId = 0;
}
if (minimumTimeSpace > timeAlreadyWaited) {
timeOutId = setTimeout(function () {
timeOutId = 0;
lastTime = now;
functionToThrottle(...args);
}, minimumTimeSpace - timeAlreadyWaited);
return;
}
lastTime = now;
functionToThrottle(...args);
};
};
const doNTimes = function (task, times) {
for (let i = 0; i < times; i += 1) {
task();
}
};
/**
Warning: does not care about arguments !
Use throttlePromiseCreator instead to handle different arguments separatly
decorates a promise creator
throttles it in a way that calls after the first
but before minimum time space
will await for the same result as the last non throttled call
*/
const forceThrottlePromiseCreator = function (promiseCreator, minimumTimeSpace = timeDefault) {
let lastTime = Number.MIN_SAFE_INTEGER;
let lastPromise;
return function (...args) {
const now = Date.now();
if (minimumTimeSpace > now - lastTime) {
return lastPromise;
}
lastTime = now;
lastPromise = promiseCreator(...args);
return lastPromise;
};
};
/**
* decorates a promise creator
* throttles it in a way that calls after the first
* but before minimum time space
* will await for the same result as the last non throttled call
* each set of argument is throttled separatly
* creates a new function for each argument set
* use this over throttlePromiseCreatorSelfClean when the argument set
* is potentially fixed and may call often the same
*/
const throttlePromiseCreator = function (promiseCreator, minimumTimeSpace = timeDefault, separator = `-`) {
const previousResults = new Map();
return function (...args) {
const argumentsAsStrings = args.map((argument) => {
try {
return JSON.stringify(argument);
} catch (typeNotHandledByJSON) {
return String(argument);
}
}).join(separator);
/*
without .map(String) works but undefined and null become empty strings
const argumentsAsStrings = args.join(separator);
*/
if (!previousResults.has(argumentsAsStrings)) {
// not yet in cache
previousResults.set(argumentsAsStrings, forceThrottlePromiseCreator(promiseCreator, minimumTimeSpace));
}
return previousResults.get(argumentsAsStrings)(...args);
};
};
/**
* decorates a promise creator
* throttles it in a way that calls after the first
* but before minimum time space
* will await for the same result as the last non throttled call
* each set of argument is throttled separatly
* creates a new function for each argument set
* eventually cleans up its unused function,
* use this over throttlePromiseCreator when the argument set
* is potentially infinite
*/
const MAXIMUM_TIMEOUT = 10 ** 3 * 60 * 60 * 24 // todo find exact number
const throttlePromiseCreatorSelfClean = function (promiseCreator, minimumTimeSpace = timeDefault, separator = `-`) {
const previousResults = new Map();
const lastCall = new Map();
const cleanUpAfterFirstCallTime = Math.min(MAXIMUM_TIMEOUT, minimumTimeSpace * 10 ** 2);
const maximumTimeToRemember = cleanUpAfterFirstCallTime - minimumTimeSpace; //must be smaller than cleanUpAfterFirstCallTime to deal with setTimeout inexact timing but bigger than 0
const setUpClean = function (argumentsAsStrings) {
return setTimeout(function () {
const now = Date.now();
if (now - lastCall.get(argumentsAsStrings) < maximumTimeToRemember) {
// was called recently clean Later
setUpClean(argumentsAsStrings);
return;
}
lastCall.delete(argumentsAsStrings);
previousResults.delete(argumentsAsStrings);
}, cleanUpAfterFirstCallTime);
};
return function (...args) {
const argumentsAsStrings = args.map((argument) => {
try {
return JSON.stringify(argument);
} catch (typeNotHandledByJSON) {
return String(argument);
}
}).join(separator);
/*
without .map(String) works but undefined and null become empty strings
const argumentsAsStrings = args.join(separator);
*/
if (!previousResults.has(argumentsAsStrings)) {
// not yet in cache
previousResults.set(argumentsAsStrings, forceThrottlePromiseCreator(promiseCreator, minimumTimeSpace));
setUpClean(argumentsAsStrings);
}
// const previousCleanId =
lastCall.set(argumentsAsStrings, Date.now())
return previousResults.get(argumentsAsStrings)(...args);
};
};
/** different than Promise.all, takes an array of functions that return a promise or value
only executes promiseCreators sequentially
resolves with an array of values or reject with the first error*/
const chainPromises = function (promiseCreators) {
const {length} = promiseCreators;
const values = [];
let i = -1;
return new Promise(function (resolve, reject) {
const chainer = function (value) {
i += 1;
if (i > 0) {
values.push(value);
}
if (i < length) {
Promise.resolve(promiseCreators[i]()).then(chainer).catch(reject);
} else {
resolve(values);
}
};
chainer();
});
};
/** forces a function that returns a promise to be sequential
useful for fs for example */
const decorateForceSequential = function (promiseCreator) {
let lastPromise = Promise.resolve();
return async function (...x) {
const promiseWeAreWaitingFor = lastPromise;
let callback;
// we need to change lastPromise before await anything,
// otherwise 2 calls might wait the same thing
lastPromise = new Promise(function (resolve) {
callback = resolve;
});
await promiseWeAreWaitingFor;
const currentPromise = promiseCreator(...x);
currentPromise.then(callback).catch(callback);
return currentPromise;
};
};
/** same as chainPromises except it will run up to x amount of
promise in parallel
resolves with an array of values or reject with the first error **/
const somePromisesParallel = function (promiseCreators, x = 10) {
const {length} = promiseCreators;
const values = [];
let i = -1;
let completed = 0;
let hasErrored = false;
return new Promise(function (resolve, reject) {
const chainer = function (isLaunching, lastValue, index) {
i += 1;
if (!isLaunching) {
values[index] = lastValue;
completed += 1;
}
if (i < length) {
const currentIndex = i;
Promise.resolve(promiseCreators[i]()).then(function (value) {
chainer(false, value, currentIndex);
}).catch(function (error) {
if (!hasErrored) {
hasErrored = true;
reject(error);
}
});
} else {
if ((completed === length) && !hasErrored) {
resolve(values);
}
}
};
// call at least once (for empty array)
chainer(true);
for (let y = 0; y < x && y < length - 1; y += 1) {
chainer(true);
}
});
};
/** different than Promise.all
only executes promiseCreator one after the previous has resolved
useful for testing
resolves with an array of values */
const chainPromiseNTimes = function (promiseCreator, times) {
return chainPromises(Array.from({length: times}).fill(promiseCreator));
};
const chainRequestAnimationFrame = function (functions) {
return new Promise(function (resolve, reject) {
const values = [];
const {length} = functions;
let i = 0;
const next = function () {
if (i < length) {
try {
values.push(functions[i]());
} catch (error) {
reject(error);
return;
}
i += 1;
requestAnimationFrame(next);
} else {
resolve(values);
}
};
next();
});
};
/** executes callback and returns time elapsed in ms */
const timeFunction = function (callback, timer = Date) {
const startTime = timer.now();
callback();
const endTime = timer.now();
return endTime - startTime;
};
/** returns a Promise that resolves with
the time elapsed for the promise to resolve and its value
executes promiseCreator and waits for it to resolve */
const timePromise = function (promiseCreator, timer = Date) {
const startTime = timer.now();
return promiseCreator().then(function (value) {
const endTime = timer.now();
return {
timeElapsed: endTime - startTime,
value,
};
});
};
/** joins together the args as strings to
decide if arguments are the same
fast memoizer
but infinitely growing */
const memoizeAsStrings = function (functionToMemoize, separator = `-`) {
const previousResults = new Map();
return function (...args) {
const argumentsAsStrings = args.map((argument) => {
try {
return JSON.stringify(argument);
} catch (typeNotHandledByJSON) {
return String(argument);
}
}).join(separator);
/*
without .map(String) works but undefined and null become empty strings
const argumentsAsStrings = args.join(separator);
*/
if (!previousResults.has(argumentsAsStrings)) {
// not yet in cache
previousResults.set(argumentsAsStrings, functionToMemoize(...args));
}
return previousResults.get(argumentsAsStrings);
};
};
/** creates a template tag function
that will map the provided function on all runtime values
before constructing the string
example:
const createURLString = createTemplateTag(encodeURIComponent)
createURLString`https://example.com/id/${`slashes and spaces are properly escaped ///`}`;
// -> "https://example.com/id/slashes%20and%20spaces%20are%20properly%20escaped%20%2F%2F%2F" */
const createTemplateTag = (mapper) => {
return (staticStrings, ...parts) => {
return Array.from(parts, (part, index) => {
return `${staticStrings[index]}${mapper(part)}`;
}).concat(staticStrings[staticStrings.length - 1]).join(``);
};
};
const textEncoder = new TextEncoder();
const bytesLengthFromString = string => {
return textEncoder.encode(string).length;
};
/** Similar to Object.assign, except it takes a white list as first argument */
const assignSelected = (list, target, ...sources) => {
sources.forEach(source => {
if (!source || typeof source !== `object`) {
return;
}
Object.entries(source).forEach(([key, value]) => {
if (key === `__proto__`) {
return;
}
if (!list.includes(key)) {
return;
}
target[key] = value;
});
});
return target;
};