TimedState.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.TimedState = void 0;
  4. /**
  5. * TimedState works similar to TimedQueue, but instead of saving
  6. * a list of all items pushed, it reduces the state on each push.
  7. */
  8. class TimedState {
  9. constructor(initState, reducer) {
  10. this.initState = initState;
  11. this.reducer = reducer;
  12. /**
  13. * State will be flushed when it reaches this number of items.
  14. */
  15. this.itemLimit = 100;
  16. /**
  17. * State will be flushed after this many milliseconds.
  18. */
  19. this.timeLimit = 5000;
  20. /**
  21. * Method that will be called when state is flushed.
  22. */
  23. this.onFlush = () => { };
  24. this.length = 0;
  25. this.state = this.initState();
  26. this.timer = null;
  27. }
  28. push(item) {
  29. this.length++;
  30. this.state = this.reducer(this.state, item);
  31. if (this.length >= this.itemLimit) {
  32. this.flush();
  33. return;
  34. }
  35. if (!this.timer) {
  36. this.timer = setTimeout(() => {
  37. this.flush();
  38. }, this.timeLimit);
  39. }
  40. }
  41. flush() {
  42. const { state, length } = this;
  43. this.state = this.initState();
  44. this.length = 0;
  45. if (this.timer)
  46. clearTimeout(this.timer);
  47. if (length) {
  48. this.timer = null;
  49. try {
  50. this.onFlush(state);
  51. }
  52. catch (error) {
  53. // tslint:disable-next-line
  54. console.error('TimedState', error);
  55. }
  56. }
  57. return state;
  58. }
  59. }
  60. exports.TimedState = TimedState;