utils.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.formatCounter = formatCounter;
  6. exports.formatTimeStr = formatTimeStr;
  7. // Countdown
  8. const timeUnits = [['Y', 1000 * 60 * 60 * 24 * 365],
  9. // years
  10. ['M', 1000 * 60 * 60 * 24 * 30],
  11. // months
  12. ['D', 1000 * 60 * 60 * 24],
  13. // days
  14. ['H', 1000 * 60 * 60],
  15. // hours
  16. ['m', 1000 * 60],
  17. // minutes
  18. ['s', 1000],
  19. // seconds
  20. ['S', 1] // million seconds
  21. ];
  22. function formatTimeStr(duration, format) {
  23. let leftDuration = duration;
  24. const escapeRegex = /\[[^\]]*]/g;
  25. const keepList = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
  26. const templateText = format.replace(escapeRegex, '[]');
  27. const replacedText = timeUnits.reduce((current, [name, unit]) => {
  28. if (current.includes(name)) {
  29. const value = Math.floor(leftDuration / unit);
  30. leftDuration -= value * unit;
  31. return current.replace(new RegExp(`${name}+`, 'g'), match => {
  32. const len = match.length;
  33. return value.toString().padStart(len, '0');
  34. });
  35. }
  36. return current;
  37. }, templateText);
  38. let index = 0;
  39. return replacedText.replace(escapeRegex, () => {
  40. const match = keepList[index];
  41. index += 1;
  42. return match;
  43. });
  44. }
  45. function formatCounter(value, config, down) {
  46. const {
  47. format = ''
  48. } = config;
  49. const target = new Date(value).getTime();
  50. const current = Date.now();
  51. const diff = down ? Math.max(target - current, 0) : Math.max(current - target, 0);
  52. return formatTimeStr(diff, format);
  53. }