智慧水务管理系统 - 精河县供水工程综合管理平台

progressEventReducer.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import speedometer from './speedometer.js';
  2. import throttle from './throttle.js';
  3. import utils from '../utils.js';
  4. export const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  5. let bytesNotified = 0;
  6. const _speedometer = speedometer(50, 250);
  7. return throttle((e) => {
  8. if (!e || typeof e.loaded !== 'number') {
  9. return;
  10. }
  11. const rawLoaded = e.loaded;
  12. const total = e.lengthComputable ? e.total : undefined;
  13. const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
  14. const progressBytes = Math.max(0, loaded - bytesNotified);
  15. const rate = _speedometer(progressBytes);
  16. bytesNotified = Math.max(bytesNotified, loaded);
  17. const data = {
  18. loaded,
  19. total,
  20. progress: total ? loaded / total : undefined,
  21. bytes: progressBytes,
  22. rate: rate ? rate : undefined,
  23. estimated: rate && total ? (total - loaded) / rate : undefined,
  24. event: e,
  25. lengthComputable: total != null,
  26. [isDownloadStream ? 'download' : 'upload']: true,
  27. };
  28. listener(data);
  29. }, freq);
  30. };
  31. export const progressEventDecorator = (total, throttled) => {
  32. const lengthComputable = total != null;
  33. return [
  34. (loaded) =>
  35. throttled[0]({
  36. lengthComputable,
  37. total,
  38. loaded,
  39. }),
  40. throttled[1],
  41. ];
  42. };
  43. export const asyncDecorator =
  44. (fn) =>
  45. (...args) =>
  46. utils.asap(() => fn(...args));