-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy patha-wrap.js
More file actions
49 lines (39 loc) · 759 Bytes
/
a-wrap.js
File metadata and controls
49 lines (39 loc) · 759 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
44
45
46
47
48
49
'use strict';
const wrap = (f) => {
let limit = 0;
let counter = 0;
const wrapper = (...args) => {
if (limit && counter === limit) wrapper.cancel();
if (!f) return null;
const res = f(...args);
counter++;
return res;
};
wrapper.cancel = () => {
f = null;
return wrapper;
};
wrapper.timeout = (msec) => {
setTimeout(() => {
wrapper.cancel();
}, msec);
return wrapper;
};
wrapper.limit = (count) => {
limit = count;
return wrapper;
};
return wrapper;
};
// Usage
const fn = (par) => {
console.log('Function called, par:', par);
};
const fn2 = wrap(fn).timeout(200).limit(3);
fn2('1st');
setTimeout(() => {
fn2('2nd');
fn2('3rd');
fn2.cancel();
fn2('4th');
}, 150);