-
Notifications
You must be signed in to change notification settings - Fork 170
/
counter.ts
121 lines (105 loc) · 2.51 KB
/
counter.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
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
/**
* @file Counter
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { Log } from '../globals'
import { Signal } from 'signals'
/**
* {@link Signal}, dispatched when the `count` changes
* @example
* counter.signals.countChanged.add( function( delta ){ ... } );
* @event Counter#countChanged
* @type {Integer}
*/
interface CounterSignals {
countChanged: Signal
}
/**
* Counter class for keeping track of counts
*/
class Counter {
count = 0
signals: CounterSignals = {
countChanged: new Signal()
}
/**
* Set the `count` to zero
* @return {undefined}
*/
clear () {
this.change(-this.count)
}
/**
* Change the `count`
* @fires Counter#countChanged
* @param {Integer} delta - count change
* @return {undefined}
*/
change (delta: number) {
this.count += delta
this.signals.countChanged.dispatch(delta, this.count)
if (this.count < 0) {
Log.warn('Counter.count below zero', this.count)
}
}
/**
* Increments the `count` by one.
* @return {undefined}
*/
increment () {
this.change(1)
}
/**
* Decrements the `count` by one.
* @return {undefined}
*/
decrement () {
this.change(-1)
}
/**
* Listen to another counter object and change this `count` by the
* same amount
* @param {Counter} counter - the counter object to listen to
* @return {undefined}
*/
listen (counter: Counter) {
this.change(counter.count)
counter.signals.countChanged.add(this.change, this)
}
/**
* Stop listening to the other counter object
* @param {Counter} counter - the counter object to stop listening to
* @return {undefined}
*/
unlisten (counter: Counter) {
const countChanged = counter.signals.countChanged
if (countChanged.has(this.change, this)) {
countChanged.remove(this.change, this)
}
}
/**
* Invole the callback function once, when the `count` becomes zero
* @param {Function} callback - the callback function
* @param {Object} context - the context for the callback function
* @return {undefined}
*/
onZeroOnce (callback: () => void, context?: any) {
if (this.count === 0) {
callback.call(context)
} else {
const fn = () => {
if (this.count === 0) {
this.signals.countChanged.remove(fn, this)
callback.call(context)
}
}
this.signals.countChanged.add(fn, this)
}
}
dispose () {
this.clear()
this.signals.countChanged.dispose()
}
}
export default Counter