throttle.js
2.4 KB
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
import { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';
export const defaultThrottleConfig = {
leading: true,
trailing: false
};
export function throttle(durationSelector, config = defaultThrottleConfig) {
return (source) => source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing));
}
class ThrottleOperator {
constructor(durationSelector, leading, trailing) {
this.durationSelector = durationSelector;
this.leading = leading;
this.trailing = trailing;
}
call(subscriber, source) {
return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
}
}
class ThrottleSubscriber extends SimpleOuterSubscriber {
constructor(destination, durationSelector, _leading, _trailing) {
super(destination);
this.destination = destination;
this.durationSelector = durationSelector;
this._leading = _leading;
this._trailing = _trailing;
this._hasValue = false;
}
_next(value) {
this._hasValue = true;
this._sendValue = value;
if (!this._throttled) {
if (this._leading) {
this.send();
}
else {
this.throttle(value);
}
}
}
send() {
const { _hasValue, _sendValue } = this;
if (_hasValue) {
this.destination.next(_sendValue);
this.throttle(_sendValue);
}
this._hasValue = false;
this._sendValue = undefined;
}
throttle(value) {
const duration = this.tryDurationSelector(value);
if (!!duration) {
this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
}
}
tryDurationSelector(value) {
try {
return this.durationSelector(value);
}
catch (err) {
this.destination.error(err);
return null;
}
}
throttlingDone() {
const { _throttled, _trailing } = this;
if (_throttled) {
_throttled.unsubscribe();
}
this._throttled = undefined;
if (_trailing) {
this.send();
}
}
notifyNext() {
this.throttlingDone();
}
notifyComplete() {
this.throttlingDone();
}
}
//# sourceMappingURL=throttle.js.map