-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
85 lines (71 loc) · 1.72 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
'use strict';
function get(arr, key) {
return findFirstPair(arr, key, function (i) {
return arr[i].value;
});
}
function set(arr, key, value) {
var found = findFirstPair(arr, key, function (i) {
arr[i].value = value;
return true;
});
if (!found) {
arr.push({key: key, value: value});
}
}
function del(arr, key) {
findFirstPair(arr, key, function (i) {
arr.splice(i, 1);
});
}
function findFirstPair(arr, key, func) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].key === key) {
return func(i);
}
}
return null;
}
module.exports = function (method, settings) {
if (!method || typeof method !== 'function') {
throw new TypeError('The first argument should be a function');
}
var interval = 0;
var maximum = null;
// keeps compatibility with initial version
if (typeof settings === 'number') {
interval = settings;
} else if (typeof settings === 'object') {
interval = settings.interval;
maximum = settings.maximum || null;
}
var executors = [];
var collectors = [];
function execute(callback) {
return setTimeout(function () {
run(callback);
}, interval);
}
function run(callback) {
method(get(collectors, callback), callback);
del(collectors, callback);
}
function aggregate(options, callback) {
var collector = get(collectors, callback) || [];
collector.push(options);
set(collectors, callback, collector);
return collector;
}
return function (options, callback) {
var collector = aggregate(options, callback);
var executor = get(executors, callback);
if (executor) {
clearTimeout(executor);
}
set(executors, callback, execute(callback));
if (maximum && collector.length >= maximum) {
clearTimeout(get(executors, callback));
run(callback);
}
};
};