utils.js 1.4 KB

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