Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

throttle.js 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';
  2. export const defaultThrottleConfig = {
  3. leading: true,
  4. trailing: false
  5. };
  6. export function throttle(durationSelector, config = defaultThrottleConfig) {
  7. return (source) => source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing));
  8. }
  9. class ThrottleOperator {
  10. constructor(durationSelector, leading, trailing) {
  11. this.durationSelector = durationSelector;
  12. this.leading = leading;
  13. this.trailing = trailing;
  14. }
  15. call(subscriber, source) {
  16. return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
  17. }
  18. }
  19. class ThrottleSubscriber extends SimpleOuterSubscriber {
  20. constructor(destination, durationSelector, _leading, _trailing) {
  21. super(destination);
  22. this.destination = destination;
  23. this.durationSelector = durationSelector;
  24. this._leading = _leading;
  25. this._trailing = _trailing;
  26. this._hasValue = false;
  27. }
  28. _next(value) {
  29. this._hasValue = true;
  30. this._sendValue = value;
  31. if (!this._throttled) {
  32. if (this._leading) {
  33. this.send();
  34. }
  35. else {
  36. this.throttle(value);
  37. }
  38. }
  39. }
  40. send() {
  41. const { _hasValue, _sendValue } = this;
  42. if (_hasValue) {
  43. this.destination.next(_sendValue);
  44. this.throttle(_sendValue);
  45. }
  46. this._hasValue = false;
  47. this._sendValue = undefined;
  48. }
  49. throttle(value) {
  50. const duration = this.tryDurationSelector(value);
  51. if (!!duration) {
  52. this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
  53. }
  54. }
  55. tryDurationSelector(value) {
  56. try {
  57. return this.durationSelector(value);
  58. }
  59. catch (err) {
  60. this.destination.error(err);
  61. return null;
  62. }
  63. }
  64. throttlingDone() {
  65. const { _throttled, _trailing } = this;
  66. if (_throttled) {
  67. _throttled.unsubscribe();
  68. }
  69. this._throttled = undefined;
  70. if (_trailing) {
  71. this.send();
  72. }
  73. }
  74. notifyNext() {
  75. this.throttlingDone();
  76. }
  77. notifyComplete() {
  78. this.throttlingDone();
  79. }
  80. }
  81. //# sourceMappingURL=throttle.js.map