-
Notifications
You must be signed in to change notification settings - Fork 375
/
countDownLatch.ts
82 lines (73 loc) · 1.9 KB
/
countDownLatch.ts
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
export interface CountDownLatchOptions
{
timeout ?: number;
}
export type CountDownLatchCallback = (isTimeout ?:boolean)=>void;
/**
* Count down to zero or timeout and invoke cb finally.
*/
export class CountDownLatch
{
count: number;
cb: CountDownLatchCallback;
timerId: any;
constructor(count : number, opts : CountDownLatchOptions, cb : CountDownLatchCallback)
{
this.count = count;
this.cb = cb;
let self = this;
if (opts.timeout)
{
this.timerId = setTimeout(function ()
{
self.cb(true);
}, opts.timeout);
}
};
/**
* Call when a task finish to count down.
*
* @api public
*/
done()
{
if (this.count <= 0)
{
throw new Error('illegal state.');
}
this.count--;
if (this.count === 0)
{
if (this.timerId)
{
clearTimeout(this.timerId);
}
this.cb();
}
};
}
/**
* Create a count down latch
*
* @param {Integer} count
* @param {Object} opts, opts.timeout indicates timeout, optional param
* @param {Function} cb, cb(isTimeout)
*
* @api public
*/
export function createCountDownLatch(count : number, cb ?: CountDownLatchCallback):CountDownLatch;
export function createCountDownLatch(count : number, opts : CountDownLatchOptions, cb ?: CountDownLatchCallback):CountDownLatch;
export function createCountDownLatch(count : number, opts ?: CountDownLatchCallback | CountDownLatchOptions, cb ?: CountDownLatchCallback)
{
if(!count || count <= 0) {
throw new Error('count should be positive.');
}
if (!cb && typeof opts === 'function') {
cb = opts;
opts = {};
}
if(typeof cb !== 'function') {
throw new Error('cb should be a function.');
}
return new CountDownLatch(count, opts as CountDownLatchOptions, cb);
};