throttle.js
3.19 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
82
83
84
85
86
87
88
89
90
/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */
import * as tslib_1 from "tslib";
import { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';
export var defaultThrottleConfig = {
leading: true,
trailing: false
};
export function throttle(durationSelector, config) {
if (config === void 0) {
config = defaultThrottleConfig;
}
return function (source) { return source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing)); };
}
var ThrottleOperator = /*@__PURE__*/ (function () {
function ThrottleOperator(durationSelector, leading, trailing) {
this.durationSelector = durationSelector;
this.leading = leading;
this.trailing = trailing;
}
ThrottleOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
};
return ThrottleOperator;
}());
var ThrottleSubscriber = /*@__PURE__*/ (function (_super) {
tslib_1.__extends(ThrottleSubscriber, _super);
function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
var _this = _super.call(this, destination) || this;
_this.destination = destination;
_this.durationSelector = durationSelector;
_this._leading = _leading;
_this._trailing = _trailing;
_this._hasValue = false;
return _this;
}
ThrottleSubscriber.prototype._next = function (value) {
this._hasValue = true;
this._sendValue = value;
if (!this._throttled) {
if (this._leading) {
this.send();
}
else {
this.throttle(value);
}
}
};
ThrottleSubscriber.prototype.send = function () {
var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
if (_hasValue) {
this.destination.next(_sendValue);
this.throttle(_sendValue);
}
this._hasValue = false;
this._sendValue = undefined;
};
ThrottleSubscriber.prototype.throttle = function (value) {
var duration = this.tryDurationSelector(value);
if (!!duration) {
this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
}
};
ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
try {
return this.durationSelector(value);
}
catch (err) {
this.destination.error(err);
return null;
}
};
ThrottleSubscriber.prototype.throttlingDone = function () {
var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
if (_throttled) {
_throttled.unsubscribe();
}
this._throttled = undefined;
if (_trailing) {
this.send();
}
};
ThrottleSubscriber.prototype.notifyNext = function () {
this.throttlingDone();
};
ThrottleSubscriber.prototype.notifyComplete = function () {
this.throttlingDone();
};
return ThrottleSubscriber;
}(SimpleOuterSubscriber));
//# sourceMappingURL=throttle.js.map